Python中zip()函数的定义及具体应用实例

zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。
实例如下:

x0=['demons','male']

y0=['selection','momentum']

#直接对一维列表进行zip操作

list(zip(x0,y0))
Out[6]: [('demons', 'selection'), ('male', 'momentum')]

#对列表的第一个元素进行zip操作

list(zip(x0[0],y0[0]))
Out[8]: [('d', 's'), ('e', 'e'), ('m', 'l'), ('o', 'e'), ('n', 'c'), ('s', 't')]

#对二维列表进行zip操作

x1=[[1,2,3,4],[5,6,7,8]]

y1=[[5,6,7,8],[1,2,3,4]]

list(zip(x1,y1))
Out[12]: [([1, 2, 3, 4], [5, 6, 7, 8]), ([5, 6, 7, 8], [1, 2, 3, 4])]

猜你喜欢

转载自blog.csdn.net/weixin_41797117/article/details/80092633