
正文
python之zip函数和sorted函数
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
# zip()函数和sorted()函数
# zip()函数:将两个序列合并,返回zip对象,可强制转换为列表或字典
# sorted()函数:对序列进行排序,返回一个排序后的新列表,原数据不改变 # 合并两个列表,以列表类型输出
list_str = ['a', 'b', 'c', 'd']
list_num = [1, 2, 3, 4]
list_new = zip(list_str, list_num)
print("zip结果(列表):", list(list_new)) # 合并两个字符串,以字典类型输出
str = 'abcd'
str2 = '1234'
list_new = zip(str, str2)
print("zip结果(字典):", dict(list_new)) # 使用zip()和sorted()对字典排序
dict_data = {'a': '4', 'b': '1', 'c': '3', 'd': '2'}
print("直接取字典最小值:", min(dict_data.items()))
print("直接对字典排序:", sorted(dict_data.items())) list_temp = zip(dict_data.values(), dict_data.keys())
print("zip处理后的最小值:", min(list_temp)) list_temp = zip(dict_data.values(), dict_data.keys())
list_temp = sorted(list_temp)
print("zip处理后的排序:", list_temp)
print("zip处理后的最小两个:", list_temp[0:2])
运行结果:
zip结果(列表): [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
zip结果(字典): {'a': '1', 'b': '2', 'c': '3', 'd': '4'}
直接取字典最小值: ('a', '4')
直接对字典排序: [('a', '4'), ('b', '1'), ('c', '3'), ('d', '2')]
zip处理后的最小值: ('1', 'b')
zip处理后的排序: [('1', 'b'), ('2', 'd'), ('3', 'c'), ('4', 'a')]
zip处理后的最小两个: [('1', 'b'), ('2', 'd')]




![【电子书】[经典小说] 《大唐双龙传》[黄玉郎][1-252全本][图片ZIP][容量2.15G] 【电子书】[经典小说] 《大唐双龙传》[黄玉郎][1-252全本][图片ZIP][容量2.15G]](https://www.04ip.com/template/qe/style/noimg/18.jpg)
![【电子书】[合集/系列] 《地狱老师》[冈野刚][1、2部全本][图片ZIP] 【电子书】[合集/系列] 《地狱老师》[冈野刚][1、2部全本][图片ZIP]](https://www.04ip.com/template/qe/style/noimg/15.jpg)
![【电子书】[合集/系列] 《小恐龙阿贡》[1-7卷全本][图片ZIP] 【电子书】[合集/系列] 《小恐龙阿贡》[1-7卷全本][图片ZIP]](https://www.04ip.com/template/qe/style/noimg/6.jpg)