600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > python zip函数_Python的zip()函数用法

python zip函数_Python的zip()函数用法

时间:2024-03-03 09:49:54

相关推荐

python zip函数_Python的zip()函数用法

Python内置一个zip函数,这里不是压缩的意思,而是将数据组合在一起,zip起来,zip本身就还有拉链的意思哦。那么,zip这个函数,组合什么呢?将多个序列组合成一个复合序列。

看下面示例代码:

>>>

>>> listA = [1,2,3]

>>> listB = [4,5,6]

>>> listA

[1, 2, 3]

>>> listB

[4, 5, 6]

>>> zip(listA,listB)

>>> list(zip(listA,listB))

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

>>>

>>> listB.append(7)

>>> listB

[4, 5, 6, 7]

>>> list(zip(listA,listB))

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

>>>

>>> list(zip(listA))

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

>>>

>>> list(zip('abcd','12345'))

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

>>>

>>> tuple(zip('abcd','12345'))

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

>>>

>>>

官方对zip函数的解释:

zip(iter1 [,iter2 [...]]) --> zip object

Return a zip object whose .__next__() method returns a tuple wherethe i-th element comes from the i-th iterable argument. The .__next__()method continues until the shortest iterable in the argument sequenceis exhausted and then it raises StopIteration.

超过两个iterable的参数也是可以的:

>>>

>>> k = zip([1,2,3],[4,5,6],[7,8,9])

>>> k

>>> list(k)

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

>>>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。