描述
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
语法
zip([iterable, ...])
参数
iterabl -- 一个或多个迭代器;
返回值
返回元组列表。
a1 = [1,2,3]
a2 = [4,5,6]
a3 = [7,8,9]
a4 = ['a','b','c','d']
zip1 = zip(a1, a2, a3) #压缩为元组
for item in zip1:
print(item)
'''
(1, 4, 7)
(2, 5, 8)
(3, 6, 9)
'''
a1 = [1,2,3]
a2 = [4,5,6]
a3 = [7,8,9]
a4 = ['a','b','c','d']
zip2 = zip(a1, a2, a4) # 以元素个数最少的列表作为长度
for item in zip2:
print(item)
'''
(1, 4, 'a')
(2, 5, 'b')
(3, 6, 'c')
'''
a1 = [1,2,3]
a2 = [4,5,6]
a3 = [7,8,9]
a4 = ['a','b','c','d']
zip3=zip(a4)
for item in zip3:
print(item)
'''
('a',)
('b',)
('c',)
('d',)
'''
a1 = [1,2,3]
a2 = [4,5,6]
a3 = [7,8,9]
a4 = ['a','b','c','d']
zip4 = zip(*a4 * 3) # zip(*) 代表解压,与zip()功能相反 *3代表输出3倍
for item in zip4:
print(item)
#二维矩阵变换(矩阵的行列互换)
l1=[[1,2,3],[4,5,6],[7,8,9]]
print([[j[i] for j in l1] for i in range(len(l1[0])) ])
for item in zip(*l1): # 与 zip 相反,可理解为解压,返回二维矩阵式
print(item)
'''
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
(1, 4, 7)
(2, 5, 8)
(3, 6, 9)
'''
标签:zip,a1,item,详解,a4,print,a2,python3 From: https://blog.51cto.com/u_15955675/6040030