zip()
是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。利用*号操作符,可以将list unzip
(解压)
>>> x=[1,2,3]
>>> y=[4,5,6]
>>> zipped=zip(x,y)
>>> zipped
<zip object at 0x0000026687053D88>
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(*zipped))
[(1, 2, 3), (4, 5, 6)]
>>> x_ylist=[]
>>> for a,b in zip(x,y):
dict={'x':a,'y':b}
x_ylist.append(dict)
>>> x_ylist
[{'x': 1, 'y': 4}, {'x': 2, 'y': 5}, {'x': 3, 'y': 6}]
>>> for a,b in zip(x,y):
dict={'x':a,'y':b}
print(dict)
{'x': 1, 'y': 4}
{'x': 2, 'y': 5}
{'x': 3, 'y': 6}
>>> x.append(9)
>>> x
[1, 2, 3, 9]
>>> y
[4, 5, 6]
>>> list(zip(x,y))
[(1, 4), (2, 5), (3, 6)]