列表
正序
a = [1,3,5,2,4,6]
a.sort() # [1, 2, 3, 4, 5, 6]
sorted(a) # [1, 2, 3, 4, 5, 6]
倒序
a = [1,3,5,2,4,6]
a.sort(reverse=True) # [6, 5, 4, 3, 2, 1]
sorted(a, reverse=True) # [6, 5, 4, 3, 2, 1]
字典
正序(按 key 排序)
d = {'a':10, 'b':30, 'c':20}
d = {'a':10, 'b':30, 'c':20}
sorted(d) # ['a', 'b', 'c']
倒序(按 key 排序)
d = {'a':10, 'b':30, 'c':20}
sorted(d, reverse=True) # ['c', 'b', 'a']
{k:d[k] for k in sorted(d, reverse=True)} # {'c': 20, 'b': 30, 'a': 10}
正序(按 value 排序)
d = {'a':10, 'b':30, 'c':20}
sorted(d, key=lambda k:d[k]) # ['a', 'c', 'b']
{k:d[k] for k in sorted(d, key=lambda k:d[k])} # {'a': 10, 'c': 20, 'b': 30}