简体   繁体   English

按降序排序python

[英]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)) :l = [name, positions]更改为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.使用zip将相应位置的项目配对。 (This will produce an iterable, so either convert to list or use sorted rather than .sort .) (这将产生一个可迭代对象,因此要么转换为列表,要么使用sorted而不是.sort 。)
  • To reverse the order, either use -x[1] as the key, or pass reverse=True .要颠倒顺序,请使用-x[1]作为键,或传递reverse=True
  • (typo) Name the position variable consistently. (打字错误)一致地命名position变量。
  • (style) Avoid using l as a variable name, as it can be confused with 1 and I . (style) 避免使用l作为变量名,因为它可能与1I混淆。
name = ["Shawn", "Patrick", "Nancy", "Viola"]
position = [3, 1, 4, 2]
l = zip(name, position)
l = sorted(l, key=lambda x: x[1], reverse=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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