排序

Sorting HOW TO

Sorting Mini-HOW TO

sorted(list, key, reverse)

使用sorted(list),在默认状态下可以对任意可迭代对象进行升序排列,返回新数组不改变原有数组。

example_list = [5, 0, 6, 1, 2, 7, 3, 4]
result_list = sorted(example_list)
print(result_list)
# [0, 1, 2, 3, 4, 5, 6, 7]

sortedkey关键字参数接受一个函数为值。该函数需要接受一个参数,并返回一个key用于排序是做比较。

# 利用key进行倒序排序
example_list = [5, 0, 6, 1, 2, 7, 3, 4]
result_list = sorted(example_list, key=lambda x: x*-1)
print(result_list)
# [7, 6, 5, 4, 3, 2, 1, 0]

# 其实简单的倒序排列通过reverse参数就能实现
result_list = sorted(example_list, reverse=True)
print(result_list)
# [7, 6, 5, 4, 3, 2, 1, 0]

使用key还可以排列复杂对象

people_group = [
    ('ecmadao', '24'),
    ('ws', '18'),
    ('boy', '7')
]

result_group = sorted(people_group, key=lambda x: int(x[1]))
print(result_group)
[('boy', '7'), ('ws', '18'), ('ecmadao', '24')]

使用itemgetter,attrgetter

itemgetter,attrgetter作用类似于上面的key,但更加高效简洁。

from operator import itemgetter, attrgetter

people_group = [
    ('ecmadao', 24),
    ('ws', 18),
    ('boy', 7)
]

result_group = sorted(people_group, key=itemgetter(1))
print(result_group)
# [('boy', 7), ('ws', 18), ('ecmadao', 24)]
# 还可以多级排序
people_group = [
    ('ecmadao', 24),
    ('ws', 18),
    ('edward', 18),
    ('boy', 7)
]
result_group = sorted(people_group, key=itemgetter(1))
print(result_group)
# [('boy', 7), ('ws', 18), ('edward', 18), ('ecmadao', 24)]
# 排序是保证为稳定的,也就是说,当多条记录拥有相同的 key 时,原始的顺序会被保留下来

result_group = sorted(people_group, key=itemgetter(1,0))
print(result_group)
# [('boy', 7), ('edward', 18), ('ws', 18), ('ecmadao', 24)]
# 元素排序后,会对有相同key值的元素通过index 0位置的value来排序

results matching ""

    No results matching ""