这是我第一次在这里提问,如果问题格式不正确,请提前道歉。我也没有太多使用 python 的经验。
我正在编写将两个列表写入 CSV 文件的代码。该代码的目的是仅当列表都包含某些内容时才将其写入文件。
我一直在尝试和错误,但发现在 python 3 中使用 ZIP
时这是可能的:
with open('file.csv', 'a') as f:
writer = csv.writer(f)
writer.writerows(zip(x,y))
f.close()
因此,如果 x
和 y
都包含某些内容,则两个列表都会写入 CSV 文件。但是,如果 x
和/或 y
不包含任何内容,则不会发生任何事情,这正是我希望代码工作的方式。
但是,我很难理解的是为什么/如何使用ZIP
来实现这一点。
非常感谢。抱歉,如果有任何不清楚的地方。
最佳答案
zip
使用最短序列。来自文档:
zip([iterable, ...])
The returned list is truncated in length to the length of the shortest argument sequence.
所以,如果你有一个空序列,你将什么也得不到:
>>> some = [1, 2, 3]
>>> empty = []
>>> zip(some, empty)
[]
使用itertools.izip_longest
如果你想使用最长的序列。对于缺失值,默认情况下它将填充 None
,或者您可以指定一个新的 fillvalue
:
itertools.izip_longest(*iterables[, fillvalue])
If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted
>>> from itertools import izip_longest
>>> some = [1, 2, 3]
>>> shorter = ['a', 'b']
>>> list(izip_longest(some, shorter))
[(1, 'a'), (2, 'b'), (3, None)]
关于python - 为什么当列表包含某些内容时,使用 zip() 仅写入 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34861553/