Python 列表排序、list排序、字典排序、dict排序

列表

正序

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}

更多排序参考

https://blog.csdn.net/weixin_39769406/article/details/110736943

猜你喜欢

转载自blog.csdn.net/u012206617/article/details/125996228