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

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)。常见的方法是什么?我应该在列表中存储元组或列表吗?


当前回答

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

reverse = True

结果如下:

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

其他回答

我在代码中使用这个:

#To sort the list based on each element's second integer (elem[1])
sorted(d2, key=lambda elem: elem[1])

根据要排序的元素,可以将其放入

(elem[*insert the index of the element you are sorting it by*])

无lambda:

def sec_elem(s):
    return s[1]

sorted(data, key=sec_elem)
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

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

reverse = True

结果如下:

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

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