我有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
(每个元素在单独的列中)
答案 0 :(得分:0)
使用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)
答案 1 :(得分:0)
这是使用带有条件的双列表理解的另一种方法:
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)))
# This function will help us differentiate strings from lists
def length(y):
if isinstance(y, str):
return 'i'
else:
return y
# We will store the lists inside a dictionnary
lists = {}
for i in range (len(list_1)):
# If we have a string we store the string otherwise we iterate
# on the list
lists[i] = [y if isinstance(y, str) else x
for y in combined_list[i] for x in length(y)]
输出:
{0: ['john', 'green', 'dog', 'cat'],
1: ['peter', 'red', 'rabbit'],
2: ['steve', 'blue', 'dog'],
3: ['mike', 'purple', ''],
4: ['paul', 'orange', 'cat', 'mouse', 'elephant']}
答案 2 :(得分:0)
list_1 = ["john", "peter", "steve", "mike", "paul"]
list_2 = ["green", "red", "blue", "purple", "orange"]
list_3 = [["dog", "cat"], "rabbit", "dog", "", ["cat", "mouse", "elephant"]]
alllist=[[l1,l2,l3] for l1,l2,l3 in zip(list_1,list_2,list_3)]
for l in alllist:
re=[]
[re.extend(item) if isinstance(item,list) else re.append(item) for item in l]
print(",".join(re))
结果
john,green,dog,cat
peter,red,rabbit
steve,blue,dog
mike,purple,
paul,orange,cat,mouse,elephant