sorted() 排序函数
程序员文章站
2022-07-15 11:03:40
...
sorted(iterable, *,key=None,reverse=False)
返回一个新的排序好的列表从可迭代对象中,
1> 例1 可以接收一个字典
sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}) # 可以生成一个新列表按照字典的key进行排序,
print(sorted({'k1': 10, 'k2': 100, 'k3': 30}))
>
[1, 2, 3, 4, 5]
['k1', 'k2', 'k3']
2> 例2 传入key参数,参数是函数名,一个一个作为该函数的实参去排序。
student_tuples = [
('john', 'A', 15),
('jame', 'B', 12),
('dave', 'B', 10)
]
a = sorted(student_tuples, key=lambda student: student[2])
print(a)
from operator import itemgetter, attrgetter
b = sorted(student_tuples, key=itemgetter(2))
print(b)
c = sorted(student_tuples, key=itemgetter(1, 2)) # 先按年级排序,再按年龄排序
print(c)
>
[('dave', 'B', 10), ('jame', 'B', 12), ('john', 'A', 15)]
[('dave', 'B', 10), ('jame', 'B', 12), ('john', 'A', 15)]
[('john', 'A', 15), ('dave', 'B', 10), ('jame', 'B', 12)
例
l1 = [ {'sales_volumn': 0},
{'sales_volumn': 108},
{'sales_volumn': 337},
{'sales_volumn': 475},
{'sales_volumn': 396},
{'sales_volumn': 172},
{'sales_volumn': 9},
{'sales_volumn': 58},
{'sales_volumn': 272},
{'sales_volumn': 456},
{'sales_volumn': 440},
{'sales_volumn': 239}]
l2 = sorted(l1, key=lambda x:x['sales_volumn'])
print(l2)