以下的list集合中的元素均为统一类型,混合类型排序暂不讨论。
eg1: type - int
>>>list1 = [1,2,4,2,5,6,3 ]
>>>list1.sort()
>>>list1
[1, 2, 2, 3, 4, 5, 6]
>>> list1.sort(reverse=True)
>>> list1
[6, 5, 4, 3, 2, 2, 1]
eg2:type - str
>>> list2 = ['abc', 'Abc', 'abC', 'aabc', 'abcc']
>>> list2.sort()
>>> list2
['Abc', 'aabc', 'abC', 'abc', 'abcc']
忽略大小写排序
>>> list2.sort(cmp=lambda x,y:cmp(x.lower(), y.lower()), reverse=True)
>>> list2
['abcc', 'Abc', 'abC', 'abc', 'aabc']
eg3: type - list 按照子list中的第二个元素进行降序排列
>>> list3 = [[1, 2, 3], [3, 1, 8], [9, 5, 2], [5, 6, 7]]
>>> list3.sort(cmp=lambda x, y:cmp(x[1], y[1]), reverse=True)
>>> list3
[[5, 6, 7], [9, 5, 2], [1, 2, 3], [3, 1, 8]]
eg4: type - dict
>>> list4 = [{'key': 'a', 'value': 123}, {'key': 'A', 'value':90}, {'key': 'aaa'
, 'value': 123}]
按照子dict里面的key对应的值进行降序排列
>>> list4.sort(cmp=lambda x, y:cmp(x['key'], y['key']), reverse=True)
>>> list4
[{'value': 123, 'key': 'aaa'}, {'value': 123, 'key': 'a'}, {'value': 90, 'key':
'A'}]
按照子dict里面的value对应的值进行升序排列
>>> list4.sort(cmp=lambda x, y:cmp(x['value'], y['value']))
>>> list4
[{'value': 90, 'key': 'A'}, {'value': 123, 'key': 'aaa'}, {'value': 123, 'key':
'a'}]