2024-03-29 13:57:49 发布
网友
所以我有一个清单如下:
example = [['b',1],['b',2],['a',2]]
它需要排序为:
即按[1]位置的数字进行数字排序。程序需要识别两个相同的数字,然后按字母顺序对这些元素进行排序。在
有什么想法吗?在
编辑:
我该如何对列表进行排序,以便先打印出最高的数字?,即:
example = [['a',2],['b',2],['b',1]]
这是一个巧妙的诀窍
>>> example = [['b',1],['b',2],['a',2]] >>> sorted(example, key=sorted) [['b', 1], ['a', 2], ['b', 2]]
只对Python有效
有两种按数字从高到低排序的方法
或者
>>> from operator import itemgetter >>> sorted(sorted(example), key=itemgetter(1), reverse=True) [['a', 2], ['b', 2], ['b', 1]]
>>> lis = [['b',1],['b',2],['a',2]] >>> sorted(lis, key=lambda x:x[::-1]) [['b', 1], ['a', 2], ['b', 2]]
要对列表进行适当排序,请使用lis.sort(...)。在
lis.sort(...)
您可以使用^{},它的key function,和^{}:
>>> from operator import itemgetter >>> example = [['b',1],['b',2],['a',2]] >>> example.sort(key=itemgetter(1,0)) >>> example [['b', 1], ['a', 2], ['b', 2]] >>>
您还可以使用^{}代替operator.itemgetter:
operator.itemgetter
但那会比较慢。在
这是一个巧妙的诀窍
只对Python有效
有两种按数字从高到低排序的方法
^{pr2}$或者
要对列表进行适当排序,请使用
lis.sort(...)
。在您可以使用^{} ,它的key function,和^{} :
您还可以使用^{} 代替
^{pr2}$operator.itemgetter
:但那会比较慢。在
相关问题 更多 >
编程相关推荐