【问题标题】:How to export all values of lists to csv on Python如何在 Python 上将列表的所有值导出到 csv
【发布时间】:2020-08-05 22:40:48
【问题描述】:
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 

我有 3 个列表,list_1 有 8 个项目,list_2 有 10 个项目,list_3 也有 10 个项目,

但是当我将列表写入 csv 时,list_2list_3 列不显示最后 2 项。

【问题讨论】:

    标签: python python-3.x list csv


    【解决方案1】:

    这是zip 的默认行为:截断到最短可迭代的长度。你可以改用zip_longest

    • 先导入:
    from itertools import zip_longest
    
    • 然后将分配cols 的行替换为:
    cols = zip_longest(list_1,list_2,list_3, fillvalue="")
    

    【讨论】:

    • 非常感谢您的帮助。
    【解决方案2】:

    你可以看到这个Link和另一个link

    传递长度不等的参数 Pythonzip()函数,注意长度很重要 你的迭代。您传入的可迭代对象可能是 参数的长度不同。

    在这些情况下,zip() 输出的元素数量将是 等于最短可迭代的长度剩余元素 zip()

    将完全忽略任何更长的迭代

    在您的情况下,您将 int 削减到第 8 个值(最排序的列表)。

    编辑

    您可以使用此信息itertools.zip_longest

    itertools.zip_longest(*iterables[, 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, '_')]
    

    【讨论】:

    • 感谢您的精彩解释。
    猜你喜欢
    • 2019-11-09
    • 2017-07-20
    • 2018-06-26
    • 2014-06-16
    • 2015-02-19
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多