Beginner’s Guide to the zip() function in Python3

  • 时间:2020-09-21 09:15:21
  • 分类:网络文摘
  • 阅读:112 次

The zip function in Python 3 takes two parameters, and generate an iterator that contains tuples. Each tuple takes a value from each input – which can be tuples or arrays. It can be illustrated as follows:

python3-zip-function Beginner's Guide to the zip() function in Python3 python

python3-zip-function

Python3 zipping two tuples

In Python2, the zip function will return all the zipped-elements in an array while in Python3, the zip function will returns an iterator – saving memory. For example,

1
2
3
4
a = (1, 2, 3)
b = (4, 5, 6)
zip(a, b) # <zip object at 0x7ff81cb770c8>
list(zip(a, b)) # [(1, 4), (2, 5), (3, 6)]
a = (1, 2, 3)
b = (4, 5, 6)
zip(a, b) # <zip object at 0x7ff81cb770c8>
list(zip(a, b)) # [(1, 4), (2, 5), (3, 6)]

As you can see in this example, the source inputs can be tuples as well. You can mix-and-match and the result is always an iterator. Then you can easily convert the iterator to array using list() or to set using the set().

zipping takes minimal length

If both inputs are of different sizes, the zip function will only zip the minimal length of both. For example,

1
2
3
4
a = (1, 2, 3, 4)
b = (4, 5, 6)
zip(a, b) # <zip object at 0x7abcdcb770c8>
set(zip(a, b)) # {(1, 4), (2, 5), (3, 6)}
a = (1, 2, 3, 4)
b = (4, 5, 6)
zip(a, b) # <zip object at 0x7abcdcb770c8>
set(zip(a, b)) # {(1, 4), (2, 5), (3, 6)}

zip nested elements

The zip function can take nested inputs as well, for example:

1
2
3
a=[(1,2),(3,4)]
b=[(5,6),(7,8)]
list(zip(a,b)) # produces [((1, 2), (5, 6)), ((3, 4), (7, 8))]
a=[(1,2),(3,4)]
b=[(5,6),(7,8)]
list(zip(a,b)) # produces [((1, 2), (5, 6)), ((3, 4), (7, 8))]

You can use the zip() function to achieve something similar of what the enumerate() does in Python.

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
春季饮食宜润肺,常吃炖梨既滋润又养人,口感甜香味道美  这道小学应用题比较难,解题关键是求相遇时间  豆腐搭配鸡蛋做出香酥可口的丸子,营养也很丰富  这道小学奥数题难倒多数学生,解题关键是比例  分享茄子的家常做法,吃起来不油腻,营养美味又下饭  中华人民共和国慈善法(主席令第四十三号)  中华人民共和国深海海底区域资源勘探开发法(主席令第四十二号)  全国人民代表大会常务委员会关于修改《中华人民共和国人口与计划生育法》的决定(主席令第四十一号)  全国人大常委会关于修改《中华人民共和国高等教育法》的决定(主席令第四十号)  中华人民共和国反家庭暴力法(主席令第三十七号) 
评论列表
添加评论