1. 列表的排序 - sort 和sorted
list1 = [3, 6, 33, 5, 2, 11]
list1.sort() # 直接改变了list1本身的
print(list1)
list2 = [3, 6, 33, 5, 2, 11]
a = sorted(list2) #并没有改变list1的值,而是生成了一个新变量
print(a)
输出:
[2, 3, 5, 6, 11, 33]
[2, 3, 5, 6, 11, 33]
2. 嵌套列表的排序
list1 = [(33, 4), (2, 11), (5, 9), (15, 7)]
list1.sort(key=lambda x: x[0]) # 按照元组中的第一个值排序
list1.sort(key=lambda x: x[1]) # 按照元组中的第二个值排序
print(list1)
list1 = [(33, 4), (2, 11), (5, 9), (15, 7)]
b = sorted(list1, key=lambda x: x[0])
print(b)
3. 字典的排序 -- sorted()
# sorted()默认是对字典的键,从小到大进行排序
dic1 = {34: 3, 2: 11, 22: 8}
e = sorted(dic1.keys()) # 只输出key值排序后的列表
print(e)
f = sorted(dic1.values()) # 只输出value值排序后的列表
print(f)
输出:
[2, 22, 34]
[3, 8, 11]
dic1 = {34: 3, 2: 11, 22: 8}
g = sorted(dic1.items(), key=lambda item: item[0]) # 按照key值排序,并输出排序后的列表
print(g)
输出:
[(2, 11), (22, 8), (34, 3)]
from operator import itemgetter
dic1 = {34: 3, 2: 11, 22: 8}
h = sorted(dic1.items(), key=itemgetter(0), reverse=False)
# itemgetter(0), 就是获取key值
# itemgetter(1), 就是获取value值
print(h)
输出:
[(2, 11), (22, 8), (34, 3)]