zip()函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象
提示Tips:本文讲解的是python3的zip()函数,该函数返回的结果是zip对象,如需展示列表,需手动 list()转换;展示字典,需手动dict()转换
语法
zip([iterable, ...])
参数
一个或多个迭代器(其中iterable,... 表示多个列表、元组、字典、集合、字符串,甚至还可以为 range()区间)
返回值
返回一个对象
实例
- nums1 = [1,2,3]
- nums2 = [4,5,6]
- zipped = zip(nums1,nums2)
- # 返回一个对象
- type(zipped) # zip object
- print(zipped) #
- # list()转换为列表
- list(zipped) # [(1, 4), (2, 5), (3, 6)]
- names = ['Andy','Rita','Lee','Odin']
- ages = [18,19,20,21]
- '''
- 并行迭代
- Andy is 18 years old
- Rita is 19 years old
- Lee is 20 years old
- Odin is 21 years old
- '''
- for name, age in zip(names,ages):
- print(name,'is',age,'years old')
如果可迭代对象的长度不相同将按短的序列为准
- nums1 = [1,2,3]
- nums3 = [4,5,6,7,8]
- # 元素个数与最短的列表一致
- list(zip(nums1,nums3)) # [(1, 4), (2, 5), (3, 6)]
- # [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
- list(zip(range(5),range(100000000)))
只要是可迭代的对象皆可相互使用,例如zip(dict,list)
注意:zip(dict)得到的只有key没有value
- tuple1 = (1,2,3,4)
- dict1 = {"a": 1, "b": 2, "c": 3}
- dict2 = {4: "d", 5: "e", 6: "f"}
- # [('a',), ('b',), ('c',)]
- print([i for i in zip(dict1)])
- # [(1, 'a'), (2, 'b'), (3, 'c')]
- print([i for i in zip(tuple1, dict1)])
- # [(1, 4), (2, 5), (3, 6)]
- print([i for i in zip(tuple1, dict2)])
扩展补充:两个列表转换成字典
- keys = ['a','b','c']
- values = [1,2,3]
- # {'a': 1, 'b': 2, 'c': 3}
- dict_nums = dict(zip(keys,values))