# 如何sorting（列表/元组）列表/元组？

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

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

` `data.sort(key=lambda tup: tup[1]) # sorts in place` `
` `from operator import itemgetter data.sort(key=itemgetter(1))` `

` `reverse = True` `

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

` `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)]` `

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

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

```  def sec_elem（s）：
返回s [2] ```

`  sort（data，key = sec_elem） `

` `data = [ ('betty', 1), ('bought', 1), ('a', 1), ('bit', 1), ('of', 1), ('butter', 2), ('but', 1), ('the', 1), ('was', 1), ('bitter', 1)]` `

` `sorted(data, key=lambda tup:(-tup[1], tup[0]))` `

` `[('butter', 2), ('a', 1), ('betty', 1), ('bit', 1), ('bitter', 1), ('bought', 1), ('but', 1), ('of', 1), ('the', 1), ('was', 1)]` `

`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` `

@斯蒂芬的答案是关键的！ 这是一个更好的可视化的例子，

` `>>> gunters = [('2044-04-05', 'parzival'), ('2044-04-07', 'aech'), ('2044-04-06', 'art3mis')] >>> gunters.sort(key=lambda tup: tup[0]) >>> print gunters [('2044-04-05', 'parzival'), ('2044-04-06', 'art3mis'), ('2044-04-07', 'aech')]` `

`key`是一个函数，将被调用来转换集合的项目进行比较..就像Java中的`compareTo`方法。

lambda的语法是lambda这个词，然后是一个可迭代的名称，然后是一个代码块。

` `tuple(sorted(t))` `