python zip() and chain()

1
2
# zip()函数的经典用法 就是将多个可迭代对象合并成一个数据段
a = zip([1,2,3],['a','b','c'],('q','w','e'))
1
2
for i in a:
print(i)
(1, 'a', 'q')
(2, 'b', 'w')
(3, 'c', 'e')
1
2
3
4
# 再举个例子
one = [1,2,3]
two = [4,5,6]
new_zip = list(zip(one, two))
1
list(zip(*new_zip))
[(1, 2, 3), (4, 5, 6)]
1
# itertools下的chain()
1
from itertools import chain
1
bb = chain([1,2,3],(4,5,6),'zxc')
1
2
for i in bb:
print(i)
1
2
3
4
5
6
z
x
c
1
# 可以看出 chain() 可以将不同的可迭代对象链接起来