1

I want to sort float numbers in descending order with the corresponding string. For e.g.

Mass=[10,45.5,56.7,34.7,12,8.2,56,78.5,5.5,21.5]
Name=['A1','A2','A3','A4','A5','A6','A7','A8','A9','A10']

Now I want to arrange mass in descending order so that it will give me

A8=78.5, A3=56.7, A7=56.....

How can I do it in python?

Many thanks

Cheers,

-Viral

2
  • Did you even try simple sorting? Commented Jul 15, 2014 at 9:18
  • yes. I did. sorted(Mass,reverse=True) Commented Jul 15, 2014 at 9:20

2 Answers 2

1

You can zip those, putting the mass in the first place, then sort them in reversed order.

for m, n in sorted(zip(Mass, Name), reverse=True):
    print n, m

Output:

A8 78.5
A3 56.7
A7 56
...
Sign up to request clarification or add additional context in comments.

1 Comment

@viralparekh Sorry for bugging you, but didn't you just accept this answer? Now its unaccepted again. What happened?
0

This code returns exactly what you want.

Mass=[10,45.5,56.7,34.7,12,8.2,56,78.5,5.5,21.5]
Name=['A1','A2','A3','A4','A5','A6','A7','A8','A9','A10']

for m,n in sorted(zip(Mass, Name), key=lambda pair: pair[0], reverse=True):
  print "%s=%s," % (n, m),

A8=78.5, A3=56.7, A7=56, A2=45.5, A4=34.7, A10=21.5, A5=12, A1=10, A6=8.2, A9=5.5,

You can use join if you don't need the colon at end.

2 Comments

key=lambda pair: pair[0] does nothing at all.
Using this approach you can specify another key if you have more then two lists. Also it less depends on arguments order in zip function (and you can change zip(Mass, Name) to zip(Name, Mass) without any frustration).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.