python - 为什么当列表包含某些内容时,使用 zip() 仅写入 CSV 文件?

标签 python csv zip

这是我第一次在这里提问,如果问题格式不正确,请提前道歉。我也没有太多使用 python 的经验。

我正在编写将两个列表写入 CSV 文件的代码。该代码的目的是仅当列表都包含某些内容时才将其写入文件。

我一直在尝试和错误,但发现在 python 3 中使用 ZIP 时这是可能的:

with open('file.csv', 'a') as f:
    writer = csv.writer(f)
    writer.writerows(zip(x,y))
    f.close()

因此,如果 xy 都包含某些内容,则两个列表都会写入 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/

相关文章:

python - 为什么 pandas.to_csv 为整数写 float ?

java - 并行读取文件时内存不足

Linux zip 不维护目录结构

c# - 如何在不使用第三方 dll 的情况下使用 dotnet framework 4.0 提取 zip 文件

python - 最好的做法是包含一个 else : pass statement at the end of a Python if or if/elif statement?

Python:仅允许设置具有 @property 装饰器的属性

python - 在 csv 文件中使用 python 格式化从 twitter api 返回的数据?

java - Java 中无需 I/O 的正确 ZIP 实现

python - 具有列表值的 Pandas 数据框列

Python 对象缓存