简体   繁体   中英

Sort in descending order python

I will like to sort by position in descending order. Given:

name = ["Shawn", "Patrick", "Nancy", "Viola"]

position = [3,1,4,2]
   
l =[name,positions]    

l.sort(key=lambda x: x[1])

Change l = [name, positions] to l = list(zip(name,position)) :

>>> name = ["Shawn", "Patrick", "Nancy", "Viola"]
>>> position = [3,1,4,2]
>>> l = list(zip(name,position))
>>> l.sort(key=lambda x: -x[1])
>>> l
[('Nancy', 4), ('Shawn', 3), ('Viola', 2), ('Patrick', 1)]

Also note the modified sort key for descending order.

  • Use zip to pair up items in corresponding positions. (This will produce an iterable, so either convert to list or use sorted rather than .sort .)
  • To reverse the order, either use -x[1] as the key, or pass reverse=True .
  • (typo) Name the position variable consistently.
  • (style) Avoid using l as a variable name, as it can be confused with 1 and I .
name = ["Shawn", "Patrick", "Nancy", "Viola"]
position = [3, 1, 4, 2]
l = zip(name, position)
l = sorted(l, key=lambda x: x[1], reverse=True)

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