def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
sentinel = object()
iterators = [iter(it) for it in iterables]
while iterators:
result = []
for it in iterators:
elem = next(it, sentinel)
if elem is sentinel:
return
result.append(elem)
yield tuple(result)
比如使用zz = zip(a,b,c,d)赋值
list()
方法:输出r的是列表x,y….. = zip()
变量个数要与元组的个数对应,而不是对应每个元组中的元素个数for i , j , k , …. in zip()
x = [1, 2, 3]
y = [4, 5, 6]
zz = zip(x, y)
print(list(zz))
[(1, 4), (2, 5), (3, 6)]
x,y….. = zip()
输出a=[1,2,3]
b=[4,5,6]
c=[7,8,9]
d=[10,11,12]
zz=zip(a,b,c,d)
x,y,z = zz
print(x)
print(y)
print(z)
输出:
(1, 4, 7, 10)
(2, 5, 8, 11)
(3, 6, 9, 12)
for 循环遍历,
a=[1,2,3]
b=[4,5,6]
c=[7,8,9]
d=[10,11,12]
zz=zip(a,b,c,d)
x,y,z = zz #
print(x)
print(y)
print(z)
for i , j , k , m in zip(a,b,c,d):
print(i,j,k,m)
输出:
(1, 4, 7, 10)
(2, 5, 8, 11)
(3, 6, 9, 12)
1 4 7 10
2 5 8 11
3 6 9 12
a=[1,2,3]
b=[4,5,6]
c=[7,8,9]
d=[10,11,12]
zz=zip(a,b,c,d)
# x,y,z = zz # 此处不能再读取zz,否则下面无法使用zz,使用时,为空列表,
若上面想使用zz,下面还要使用则重新zip打包,再zip(*zip((a,b,c,d))
# for i , j , k in zip(*zip(a,b,c,d)):
for i , j , k in zip(*zz):
print(i,j,k)
输出:
1 2 3
4 5 6
7 8 9
10 11 12
zip(*zz) 为逆过程:类似矩阵的转置
a=[1,2,3]
b=[4,5,6]
c=[7,8,9]
d=[10,11,12]
zz=zip(a,b,c,d)
print(list(zip(*zz)))
输出:[(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12)]
因变使用list(),输出结果是由元组组成的列表
=========================================
a=[1,2,3]
b=[4,5,6]
c=[7,8,9]
d=[10,11,12]
zz=zip(a,b,c,d)
# print(list(zip(*zz))) # 若下面再次使用zz时此行需注释掉
x,y,z,s = zip(*zz)
print(x)
print(y)
print(z)
print(s)
输出:
(1, 2, 3)
(4, 5, 6)
(7, 8, 9)
(10, 11, 12)
(1)过程:
逐一取出每个列表里的第i个元素,组成第i个新元组,
当列表不等长时,剩余的元素就被舍弃。
zip(*zip())类似于矩阵的转置操作
(2)打包的元素可以为:
列表[] 元组() 集合{ }
(3)当打包元素为集合{},且{}中的元素为True False None 数字时:
会自动对多余的True或False进行舍弃,最终zip()里只能保留最多四种值:True False None 数字,
数字1被认为True,0被认为False,但当同时存在True与1,舍1,同时存在False与0,舍0,当True与1或False与0不同时存在,则保留1或0。
而其它非0数字均被识别,但是组合位置不一定。
集合 {}设置不同的数字演示
# {}设置不同的数字演示
aa = [1,2,3,4,5]
bb = ["11","22","33","44",'55']
set = {True,False,None,True,0}
zz = zip(aa,bb,set) # 打包
print(list(zz))
输出:
[(1, '11', False), (2, '22', True), (3, '33', None)]
set = {True,False,None,True,1}
输出:
[(1, '11', False), (2, '22', True), (3, '33', None)]
set = {True,False,None,True,2}
输出:
[(1, '11', False), (2, '22', True), (3, '33', 2), (4, '44', None)]
set = {True,False,None,True,6}
输出:
[(1, '11', False), (2, '22', True), (3, '33', None), (4, '44', 6)]
set = {True,False,None,True,-1}
输出:
[(1, '11', False), (2, '22', True), (3, '33', None), (4, '44', -1)]
集合{}设置 0和1与False与True的演示
aa = [1,2,3,4,5]
bb = ["11","22","33","44",'55']
set = {False,False,None,False,0}
zz = zip(aa,bb,set) # 打包
print(list(zz))
输出:
[(1, '11', False), (2, '22', None)]
set = {False,False,None,False,1}
输出:
[(1, '11', False), (2, '22', 1), (3, '33', None)]
aa = [1,2,3,4,5]
bb = ["11","22","33","44",'55']
set = {True,True,None,True,1}
zz = zip(aa,bb,set) # 打包
print(list(zz))
输出:
[(1, '11', True), (2, '22', None)]
set = {True,True,None,True,0}
输出:
[(1, '11', 0), (2, '22', True), (3, '33', None)]