我在列表或元组列表中有一些数据,如下所示:

data = [[1,2,3], [4,5,6], [7,8,9]]
data = [(1,2,3), (4,5,6), (7,8,9)]

我想按子集中的第二个元素排序。意思是,按2,5,8排序,其中2来自(1,2,3),5来自(4,5,6)。常见的方法是什么?我应该在列表中存储元组或列表吗?


当前回答

sorted_by_second = sorted(data, key=lambda tup: tup[1])

or:

data.sort(key=lambda tup: tup[1])  # sorts in place

默认排序模式为升序。要按降序排序,请使用选项reverse=True:

sorted_by_second = sorted(data, key=lambda tup: tup[1], reverse=True)

or:

data.sort(key=lambda tup: tup[1], reverse=True)  # sorts in place

其他回答

sorted_by_second = sorted(data, key=lambda tup: tup[1])

or:

data.sort(key=lambda tup: tup[1])  # sorts in place

默认排序模式为升序。要按降序排序,请使用选项reverse=True:

sorted_by_second = sorted(data, key=lambda tup: tup[1], reverse=True)

or:

data.sort(key=lambda tup: tup[1], reverse=True)  # sorts in place

对于按多个条件排序,例如按元组中的第二个和第三个元素排序,让

data = [(1,2,3),(1,2,1),(1,1,4)]

因此定义一个lambda,它返回一个描述优先级的元组,例如

sorted(data, key=lambda tup: (tup[1],tup[2]) )
[(1, 1, 4), (1, 2, 1), (1, 2, 3)]

斯蒂芬的答案是我会用的。为了完整起见,这里是DSU(修饰排序-未修饰)模式和列表理解:

decorated = [(tup[1], tup) for tup in data]
decorated.sort()
undecorated = [tup for second, tup in decorated]

或者,更简洁地说:

[b for a,b in sorted((tup[1], tup) for tup in data)]

正如Python Sorting HowTo中所指出的,自从Python 2.4之后,当关键函数可用时,这是不必要的。

itemgetter()比lambda tup:tup[1]稍快,但增长相对温和(约10%至25%)。

(IPython会话)

>>> from operator import itemgetter
>>> from numpy.random import randint
>>> values = randint(0, 9, 30000).reshape((10000,3))
>>> tpls = [tuple(values[i,:]) for i in range(len(values))]

>>> tpls[:5]    # display sample from list
[(1, 0, 0), 
 (8, 5, 5), 
 (5, 4, 0), 
 (5, 7, 7), 
 (4, 2, 1)]

>>> sorted(tpls[:5], key=itemgetter(1))    # example sort
[(1, 0, 0), 
 (4, 2, 1), 
 (5, 4, 0), 
 (8, 5, 5), 
 (5, 7, 7)]

>>> %timeit sorted(tpls, key=itemgetter(1))
100 loops, best of 3: 4.89 ms per loop

>>> %timeit sorted(tpls, key=lambda tup: tup[1])
100 loops, best of 3: 6.39 ms per loop

>>> %timeit sorted(tpls, key=(itemgetter(1,0)))
100 loops, best of 3: 16.1 ms per loop

>>> %timeit sorted(tpls, key=lambda tup: (tup[1], tup[0]))
100 loops, best of 3: 17.1 ms per loop

如果你想将数组从高到低排序,我只想添加到Stephen的答案中,除了上面的注释之外,另一种方法就是将其添加到行中:

reverse = True

结果如下:

data.sort(key=lambda tup: tup[1], reverse=True)