python3 sorted().py

"""
模块:python3 sorted().py
功能:python3 排序函数。
参考:https://www.runoob.com/python3/python3-func-sorted.html
知识点:
1.sorted(iterable, key=None, reverse=False) -> 一个新的 list.
sorted() 函数对所有可迭代的对象进行排序操作。
2.sort 与 sorted 区别:
sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
list 的 sort 方法返回的是对已经存在的列表进行操作,
而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。
"""
# 1.sorted()
# 此方法不改变原始序列,返回新的序列。
print("1:")
list1 = [5, 2, 3, 1, 4]
list2 = sorted(list1)
print(list1, list2)
# [5, 2, 3, 1, 4] [1, 2, 3, 4, 5]
print(sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}))
# [1, 2, 3, 4, 5]
list1 = [5, 0, 6, 1, 2, 7, 3, 4]
print(sorted(list1, key=lambda x: x * -1))
# [7, 6, 5, 4, 3, 2, 1, 0]
print(sorted(list1, reverse=True))
# [7, 6, 5, 4, 3, 2, 1, 0]
print(sorted({1, 3, 2, 4}))
# [1, 2, 3, 4]

# 2.list.sort() -> None
# 此方法,改变了原始的列表,返回值 None。
print("2:")
a = [5, 2, 3, 1, 4]
print(a)
# [5, 2, 3, 1, 4]
a.sort()
print(a)
# [1, 2, 3, 4, 5]
发布了197 篇原创文章 · 获赞 61 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/weixin_42193179/article/details/104552249