Python 列表的排序

python list 的排序函数

>>> a = [2,4,6,7,4,3,9]
>>> a.sort()
>>> a
[2, 3, 4, 4, 6, 7, 9]
>>>

元素是元组的list 排序

(使用每个元组的第一个(第二个)元素排序<正序><倒序>)

>>> c=[23,45,21,4,54,3]
>>> d=[43,34,56,2,12,9]
>>> b=zip(c,d)
>>> b
[(23, 43), (45, 34), (21, 56), (4, 2), (54, 12), (3, 9)]
>>> b.sort(lambda x,y:cmp(x[0],y[0]))
>>> b
[(3, 9), (4, 2), (21, 56), (23, 43), (45, 34), (54, 12)]
>>> b.sort(lambda x,y:cmp(y[0],x[0]))
>>> b
[(54, 12), (45, 34), (23, 43), (21, 56), (4, 2), (3, 9)]
>>> b.sort(lambda x,y:cmp(x[1],y[1]))
>>> b
[(4, 2), (3, 9), (54, 12), (45, 34), (23, 43), (21, 56)]
>>> b.sort(lambda x,y:cmp(y[1],x[1]))
>>> b
[(21, 56), (23, 43), (45, 34), (54, 12), (3, 9), (4, 2)]
>>>
sort函数参数可以是函数,这里使用匿名函数

你可能感兴趣的:(python)