首页 > 解决方案 > 将嵌套列表的每个元素写入 CSV 的单独列

问题描述

我有 3 个长度为 n 的列表,我想将它们组合成一个列表,然后将所有第 n 个索引组合在一个列表中,并在 csv 文件的单独列中生成每个元素的输出

list_1 = ["john", "peter", "steve", "mike", "paul"]
list_2 = ["green", "red", "blue", "purple", "orange"]
list_3 = [["dog", "cat"], "rabbit", "dog", "", ["cat", "mouse", "elephant"]

到目前为止,我使用过:

combined_list = list(map(list, zip(list_1, list_2, list_3)))

将列表合并为一个。

如果我尝试:

for items in combined_list:
    writer.writerow(items)

我得到:

john,green,"['dog', 'cat']"
peter,red,rabbit
steve,blue,dog
mike,purple,
paul,orange,"['cat', 'mouse', 'elephant']"

预期输出:

john, green, dog, cat
peter, red, rabbit
steve, blue, dog
mike, purple, 
paul, orange, cat, mouse, elephant

(每个元素在一个单独的列中)

标签: python

解决方案


用于isinstance检查最后一项是否为列表,如果扩展,则按原样使用列表。

前任:

list_1 = ["john", "peter", "steve", "mike", "paul"]
list_2 = ["green", "red", "blue", "purple", "orange"]
list_3 = [["dog", "cat"], "rabbit", "dog", "", ["cat", "mouse", "elephant"]]

combined_list = list(map(list, zip(list_1, list_2, list_3)))
for items in combined_list:
    if isinstance(items[-1], list):              #Check if last element is list. 
        writer.writerow(items[:-1] + items[-1])
    else:
        writer.writerow(items)

推荐阅读