概念
zip() 函数⽤于将可迭代的对象作为参数,将对象中对应的元素打包成⼀个个元组,然后返回由这些元组组成的列表(python2.x的定义)。
特别注意:
python3.x的定义与python2.x定义的主要区别是返回值,在python3.x为了减少内存,返回的是⼀个zip对象,可以⽤list、dict等进⾏转换。如果各个迭代器的元素个数不⼀致,则返回列表长度与最短的对象相同,利⽤ * 号操作符,可以将元组解压为列表(也叫减包运算)。
语法
zip([iterable, ...])
参数说明:
iterabl -- ⼀个或多个可迭代对象
iterable,... 表⽰多个列表、元组、字典、集合、字符串,甚⾄还可以为 range() 区间iterable中可以为不同的数据类型多个迭代器之间⽤逗号隔开
返回值
返回元组列表(python2.x)
返回zip对象(其实这⾥就是⼀个迭代器)(python3.x)
例如:
list_3 = [11, 12, 13, 14, 15]print(next(list_3))执⾏结果:
TypeError: 'list' object is not an iterator
可以看出zip()返回的就是迭代器对象,若是可迭代对象是没有next()⽅法的,就像上⾯的报错,换成迭代器就不会报错了 实例
同⼀数据类型
list_1 = [1, \"str\", 3, 4, 5]list_2 = [6, 7, 8, 9, 10]
list_3 = [11, 12, 13, 14, 15]
result = list(zip(list_1, list_2, list_3))print(result)
执⾏结果:
[(1, 6, 11), ('str', 7, 12), (3, 8, 13), (4, 9, 14), (5, 10, 15)]
不同数据类型
list_1 = [1, \"str\", 3, 4, 5]list_2 = [6, 7, 8, 9, 10]
list_3 = [11, 12, 13, 14, 15]
dict_4 = {\"张三\": 18, \"王五\": 19, \"赵四\": 18, \"王琦\": 19, \"王虎\": 18, \"张六\": 19}tuple_5 = {\"a\", \"b\", \"c\", \"d\", \"e\"}set_6 = {20, 30, 40, 50, 60}
result = list(zip(list_1, list_2, list_3, dict_4, tuple_5,set_6))print(result)
执⾏结果:
[(1, 6, 11, '张三', 'b', 40), ('str', 7, 12, '王五', 'd', 50), (3, 8, 13, '赵四', 'c', 20), (4, 9, 14, '王琦', 'a', 60), (5, 10, 15, '王虎', 'e', 30)]
不同长度的同⼀数据类型
list_1 = [1, \"str\", 3, 4, 5]list_2 = [6, 7, 8, 9, 10]list_3 = [11, 12]
result = list(zip(list_1, list_2, list_3))print(result)执⾏结果:
[(1, 6, 11), ('str', 7, 12)]
不同长度的不同类型
list_1 = [1, \"str\", 3, 4, 5]list_2 = [6, 7, 8, 9, 10]list_3 = [11, 12]
dict_4 = {\"张三\": 18, \"王五\": 19, \"赵四\": 18, \"王琦\": 19, \"王虎\": 18, \"张六\": 19}tuple_5 = {\"a\", \"b\", \"c\", \"d\", \"e\"}set_6 = {20, 30, 40}
result = list(zip(list_1, list_2, list_3, dict_4,tuple_5,set_6))print(result)
执⾏结果:
[(1, 6, 11, '张三', 'b', 40), ('str', 7, 12, '王五', 'e', 20)]
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- kqyc.cn 版权所有 赣ICP备2024042808号-2
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务