简体   繁体   中英

How do you sort a list of numbers in descending order

Say I've got a file with multiple names and integers like so:

name1:5
name2:3
name3:10

How can I add this to a dictionary, and then print it in descending order (eg highest value to lowest value)

Assuming by list you meant dict , this is what you want:

 names={'name1':5, 'name2':3, 'name3':10}
 print sorted(names, key=lambda x:names[x], reverse=True)

As another poster pointed out, the original poster requested to print out both the name & it's value. To accomplish this, change the code to:

 names={'name1':5, 'name2':3, 'name3':10}
 for name in sorted(names, key=lambda x:names[x], reverse=True):
     print name, names[name]

You need to specify an appropriate key function for the builtin sorted :

# I assume this is what your input looks like
input = ["name1:5", "name2:3", "name3:10"]
output = sorted(input, key=lambda x: int(x.split(":")[1]), reverse=True)

i got your point what you are saying and how it is done is given below :)

a=[name1:5, name2:3, name3:10]
def Last(s):
   return s[-1]
sorted(a, key=Last)

and then in this way you can sort it in reverse ..as per your choice ..enjoy :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM