如何在Python中将所有列表值导出到CSV?

4
list_1 = ['1','2','3','4','5','6','7','8']
list_2 = ['n1','n2','n3','n4','n5','n6','n7','n8','n9','n10']
list_3 = ['o1','o2','o3','o4','o5','o6','o7','o8','o9','o10']

cols = zip(list_1,list_2,list_3)

with open('file.csv', 'w', newline='') as f:
    thewriter = csv.writer(f)

    thewriter.writerow(['list_1','list_2','list_3'])
    for col in cols:
       thewriter.writerow(col)

输出

list1   list2   list3
  1      n1      o1
  2      n2      o2
  3      n3      o3
  4      n4      o4
  5      n5      o5
  6      n6      o6
  7      n7      o7
  8      n8      o8

预期输出

list1   list2   list3
  1      n1      o1
  2      n2      o2
  3      n3      o3
  4      n4      o4
  5      n5      o5
  6      n6      o6
  7      n7      o7
  8      n8      o8
         n9      o9
         n10     o10 

我有三个列表,list_1 有8个项目,list_2list_3 各有10个项目。但是当我将这些列表写入csv文件时,list_2list_3 列不会显示最后两个项目。
2个回答

5

zip 的默认行为是截断到最短可迭代对象的长度。您可以使用zip_longest 替代它:

  • 首先导入 itertools 模块:
from itertools import zip_longest
  • 然后用以下代码替换分配 cols 的那一行:
cols = zip_longest(list_1,list_2,list_3, fillvalue="")

1
非常感谢您的帮助。 - Victor

3

您可以看到这个链接和另一个链接

传递长度不相等的参数 当您使用Python的zip()函数时,重要的是要注意您可迭代对象的长度。您传递为参数的可迭代对象可能长度不同。

在这些情况下,zip()输出的元素数量将等于最短可迭代对象的长度。任何更长的可迭代对象中剩余的元素都会被zip()完全忽略。

在您的情况下,您将得到被截断为第8个值 (即最短列表) 的整数。

编辑

您可以使用此信息 itertools.zip_longest

itertools.zip_longest(*iterables[, fillvalue])

创建一个聚合每个可迭代对象的元素的迭代器。如果可迭代对象长度不同,则缺失的值将用fillvalue填充。迭代将继续,直到最长的可迭代对象耗尽。等效于:

def zip_longest(*args, fillvalue=None):
     # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
     def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
         yield counter()         # yields the fillvalue, or raises IndexError
     fillers = repeat(fillvalue)
     iters = [chain(it, sentinel(), fillers) for it in args]
     try:
         for tup in zip(*iters):
            yield tup
     except IndexError:
         pass

如果其中一个可迭代对象可能是无限的,则应该将zip_longest()函数包装在限制调用次数的东西中(例如islice()或takewhile())。如果未指定,fillvalue默认为None。
示例:
from itertools import zip_longest

l_1 = [1, 2, 3]
l_2 = [1, 2]

combinated = list(zip_longest(l_1, l_2, fillvalue="_"))

print(combinated)  # [(1, 1), (2, 2), (3, '_')]

感谢您的精彩解释。 - Victor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接