Python:对dict、list、tuple中的元素排序
一)对字典中元素排序
方法一:利用sorted的key参数进行排序
from random import randint
date = {k:randint(0, 20) for k in range(10)}
c = sorted(date.items(), key = lambda k:k[1])
print(c)
- sorted(date.items(), key = lambda k:k[1]):key参数来指定用来参与比较的数;k:k[1],表示传入(key, value),取返回value,即k[1];
方法二:将字典的key和value成对转换为元组,队每个元组进行比较(逐个元素进行比较,知道分出大小)
from random import randint
date = {k:randint(0, 20) for k in range(10)}
c1 = zip(date.values(), date.keys())
c2 = sorted(c1)
print(c1)
- zip(date.values(), date.keys()):用zip()内置函数,将date的所有key和value成对转成元组:(key, value);
二)队list、tuple中元素排序
a = [randint(0,20) for _ in range(10)]
print(sorted(a, reverse = True))
- reverse = True,按从大到小;reverse = False,从小到大,reverse默认为True