python中zip()函数基本用法

zip()函数接受一系列可迭代对象作为参数,将不同对象中相对应的元素打包成一个元组(tuple),返回由这些元组组成的list列表,如果传入的参数的长度不等,则返回的list列表的长度和传入参数中最短对象的长度相同。

举例1

x = [1,2,3,4,5]
y = ['a','b','c','d']
xy = zip(x,y)
print xy
for a,b in zip(x,y):
    print a
    print b


输出:

[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
1
a
2
b
3
c
4
d


举例2

x = [1,2,3,4,5]
xx = zip(x)
print xx
for a in zip(x):
    print a
for a in zip(x):
    print a[0]


输出:

[(1,), (2,), (3,), (4,), (5,)]
(1,)
(2,)
(3,)
(4,)
(5,)
1
2
3
4
5



举例3

x = [[1,2,3,4],['a','b','c'],[7,8,9]]
y = zip(*x)
print y
for a in y:
    print a
for a,b,c in zip(*x):
    print a
    print b
    print c


输出:

[(1, 'a', 7), (2, 'b', 8), (3, 'c', 9)]
(1, 'a', 7)
(2, 'b', 8)
(3, 'c', 9)
1
a
7
2
b
8
3
c
9

转载于:https://www.cnblogs.com/mtcnn/p/9411777.html

你可能感兴趣的:(python中zip()函数基本用法)