为什么在列表包含某些内容时使用 zip() 只写入 CSV 文件?
Why does using zip() only write to CSV file when list contains something?
这是我第一次在这里提问,如果我没有正确格式化问题,请提前致歉。我也没有太多使用 python.
的经验
我正在编写将两个列表写入 CSV 文件的代码。代码的目的是让列表仅在它们都包含某些内容时才写入文件。
我一直在反复试验,但发现在 python 3 中使用 ZIP
时可以做到这一点 3:
with open('file.csv', 'a') as f:
writer = csv.writer(f)
writer.writerows(zip(x,y))
f.close()
因此,如果 x
和 y
都包含某些内容,则两个列表都会写入 CSV 文件。但是,如果 x
and/or y
不包含某些内容,则什么也不会发生,这正是我希望代码工作的方式。
但是,我很难理解的是WHY/HOW使用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.
的经验我正在编写将两个列表写入 CSV 文件的代码。代码的目的是让列表仅在它们都包含某些内容时才写入文件。
我一直在反复试验,但发现在 python 3 中使用 ZIP
时可以做到这一点 3:
with open('file.csv', 'a') as f:
writer = csv.writer(f)
writer.writerows(zip(x,y))
f.close()
因此,如果 x
和 y
都包含某些内容,则两个列表都会写入 CSV 文件。但是,如果 x
and/or y
不包含某些内容,则什么也不会发生,这正是我希望代码工作的方式。
但是,我很难理解的是WHY/HOW使用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)]