python - 将嵌套列表的每个元素写入 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
(每个元素在一个单独的列中)
解决方案
用于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)
推荐阅读
- sql - ORACLE - 从 VARRAY OF REF 对象中选择数据
- linux - 比较倍数 vars shell linux 的最佳方法
- php - 使用 glob 函数循环 xml 文件仅循环文件夹中的最后一个文件
- clang - 看似不必要的 bitcast -> phi -> 正在生成 bitcast
- android - 如何在android中向电子邮件意图添加动态锚链接和超链接
- html - content_tag :我没有显示 rails fontawesome
- kotlin - 解构而不是 .bind() 在 Arrow Monad 理解中不起作用
- java - 无法使用改造 REST API,出现 IllegalStateException:请帮我调查
- c++ - 将struct c++程序转换为c语言
- javascript - 如何以这样的方式制作对象数组,使用户连续重复的对象形成一个新数组