zip
和 zip_longest
都是 Python 中用于处理迭代器的函数,它们都可以将多个迭代器中的元素打包成一个个元组,然后返回这些元组的迭代器¹²。但是,它们在处理长度不一致的迭代器时的行为是不同的:
zip
:当zip
函数处理长度不一致的迭代器时,它会在最短的迭代器耗尽时停止,忽略掉其他迭代器中多出来的元素¹²。zip_longest
:zip_longest
函数(来自itertools
模块)会继续迭代,直到最长的迭代器耗尽。对于短的迭代器已经耗尽的部分,zip_longest
会用一个特定的值(默认为None
)来填充¹²。
例如,假设我们有两个列表 x = [1, 2, 3, 4, 5, 6, 7]
和 y = [8, 9, 10]
,我们可以使用 zip
和 zip_longest
来打包这两个列表:
使用 zip
:
x = [1, 2, 3, 4, 5, 6, 7]
y = [8, 9, 10]
z = list(zip(x, y))
print(z) # 输出:[(1, 8), (2, 9), (3, 10)]
使用 zip_longest
:
from itertools import zip_longest
x = [1, 2, 3, 4, 5, 6, 7]
y = [8, 9, 10]
z = list(zip_longest(x, y))
print(z) # 输出:[(1, 8), (2, 9), (3, 10), (4, None), (5, None), (6, None), (7, None)]
你可以看到,当 y
列表的元素用完后,zip
函数停止迭代,而 zip_longest
使用 None
来填充 y
的位置¹。希望这个解释能帮助你理解!
zip
和 zip_longest
的使用取决于你的具体需求。
- 如果你处理的迭代器长度一致,或者你只关心所有迭代器都有值的部分,那么
zip
就足够了。zip
在最短的迭代器耗尽时就会停止,忽略掉其他迭代器中多出来的元素。 - 如果你处理的迭代器长度不一致,而你又希望得到所有的元素(即使某些迭代器已经耗尽),那么
zip_longest
会更适合。zip_longest
会继续迭代,直到最长的迭代器耗尽。对于短的迭代器已经耗尽的部分,zip_longest
会用一个特定的值(默认为None
)来填充。
(1) python - Zip and Zip Longest - Stack Overflow. https://stackoverflow.com/questions/59119751/zip-and-zip-longest.
(2) python - Is there a middle ground between zip and `zip_longest .... https://stackoverflow.com/questions/13341224/is-there-a-middle-ground-between-zip-and-zip-longest.
(3) What is the difference between “zip” and “zip_longest” in Python?. https://www.devquarters.com/what-is-the-difference-between-zip-and-zip_longest-in-python/.
(4) Python zip() Function – Explained with Code Examples - freeCodeCamp.org. https://www.freecodecamp.org/news/the-zip-function-in-python-explained-with-examples/.
(5) undefined. https://raw.githubusercontent.com/muriloasouza/Deep-Learning/master/Input.txt.
(6) undefined. https://raw.githubusercontent.com/muriloasouza/Deep-Learning/master/Labels.txt.
(7) undefined. https://raw.githubusercontent.com/muriloasouza/Deep-Learning/master/Input_Train.txt.
(8) undefined. https://raw.githubusercontent.com/muriloasouza/Deep-Learning/master/Labels_Train.txt.
(9) undefined. https://raw.githubusercontent.com/muriloasouza/Deep-Learning/master/Input_Valid.txt.
(10) undefined. https://raw.githubusercontent.com/muriloasouza/Deep-Learning/master/Labels_Valid.txt.