首页 > 编程语言 > 详细

python之zip函数和sorted函数

时间:2017-07-30 00:41:19      阅读:289      评论:0      收藏:0      [点我收藏+]
# 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‘)]

 

python之zip函数和sorted函数

原文:http://www.cnblogs.com/gongxr/p/7257953.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!