physics_for_all
physics_for_all

Reputation: 2263

Python arrange numbers with corresponding string

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

Upvotes: 1

Views: 126

Answers (2)

jmistx
jmistx

Reputation: 11

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.

Upvotes: 0

tobias_k
tobias_k

Reputation: 82929

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
...

Upvotes: 1

Related Questions