3
statlist = [('abc',5,1), ('bzs',66,1), ... ]
sorted(statlist, key=lambda x: int(x[1]))

我想按从最大到最小的整数对其进行排序。在本例中,为 5 和 66。但它似乎不起作用。

4

8 回答 8

7

sorted函数返回一个列表,因此您需要像这样分配函数的结果:

new_list = sorted(statlist, key=lambda x: int(x[1])) 
于 2009-11-29T13:24:08.457 回答
7

使用.sort就地排序的方法:

statlist = [('abc',5,1), ('bzs',66,1), ... ]
statlist.sort(key=lambda x: int(x[1]))

如果您确实想使用sorted,请重新分配变量:

statlist = [('abc',5,1), ('bzs',66,1), ... ]
statlist = sorted(statlist, key=lambda x: int(x[1]))

对于降序排序,请使用reverse

statlist = [('abc',5,1), ('bzs',66,1), ... ]
statlist = sorted(statlist, key=lambda x: int(x[1]), reverse=True)

然后,你最好使用itemgetter而不是 a lambda

import operator
statlist = [('abc',5,1), ('bzs',66,1), ... ]
statlist = sorted(statlist, key=operator.itemgetter(1), reverse=True)
于 2009-11-29T13:27:22.783 回答
3

您可以传递、键和反向到 .sort 函数

>>> x.sort(key=lambda x:x[1],reverse=True)
>>> x
[('bzs', 66, 1), ('abc', 5, 1)]
>>>
于 2009-11-29T13:25:08.033 回答
3

用于就地排序

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

用于创建其他列表,使用排序数据

otherlist = sorted( statlist, key=lambda x: x[1] )
于 2009-11-29T13:27:41.233 回答
2
from operator import itemgetter
statlist = [('abc',5,1), ('bzs',66,1), ... ]

# statlist.sort modifiest the statlist, sorted returns a new one
# reverse puts the largest items to the front
statlist.sort(key=itemgetter(1), reverse=True)
于 2009-11-29T13:27:40.193 回答
1

在回应 alex 的评论时,他认为 sorted() 的工作方式“类似于 sort 函数”:

如果它“像排序功能一样”工作,那么它不太可能被放入库中。

无论如何,没有排序功能......你指的是列表对象的排序方法

使用交互式解释器的简单演示:

>>> alist = [3, 2, 1]; x = alist.sort(); print x; print alist
None
[1, 2, 3]
>>> alist = [3, 2, 1]; x = sorted(alist); print x; print alist
[1, 2, 3]
[3, 2, 1]

这里有一个提示:寻找模式和相似之处,但始终验证您的直观推断。您可能希望将这些想法应用于reversereversed

于 2009-11-30T04:21:30.990 回答
0
>>> s = [('xyz', 8, 1), ('abc',5,1), ('bzs',66,1) ]
>>> s = sorted(s, key=lambda x: int(x[1]))
>>> s.reverse()
>>> print s
[('bzs', 66, 1), ('xyz', 8, 1), ('abc', 5, 1)]
于 2009-11-29T13:26:54.667 回答
0

嘿,当我将某些东西保存到数组时,我不会担心顺序,然后最后我会使用sorted()这样的例子statlist = sorted(statlist),如果你想要它从大到小statlist = sorted(statlist, reverse = True)这是从大到小的简单方法!

我使用过的示例代码(只是摘录)

    while i <= math.sqrt(intnum):
        if (intnum % i) == 0:
            numbers.insert(0,i)
            numbers.insert(0,int(intnum/i))
            print(i,":", int(intnum/i))
        i += 1
    numbers = sorted(numbers, reverse = True)
于 2014-04-27T13:22:49.963 回答