如何将多列表合并后的嵌套元素拆分写入CSV独立列?
To get each nested element into its own CSV column, you need to flatten the nested lists in each row before writing to the file. Your current approach writes the entire nested list as a single cell because the CSV writer doesn't automatically split list elements—you have to explicitly expand them first.
Here's a complete solution that handles both flat and nested elements (even multi-level nested lists):
import csv # Your original lists list_1 = ["john", "peter", "steve", "mike", "paul"] list_2 = ["green", "red", "blue", "purple", "orange"] list_3 = [["dog", "cat"], "rabbit", "dog", "", ["cat", "mouse", "elephant"]] def flatten_element(item): """Recursively flatten any nested lists into a flat list of elements.""" flattened = [] if isinstance(item, list): for sub_item in item: flattened.extend(flatten_element(sub_item)) else: flattened.append(item) return flattened # Write to CSV with open('output.csv', 'w', newline='', encoding='utf-8') as csv_file: writer = csv.writer(csv_file) # Iterate through corresponding elements of all three lists for name, color, third_item in zip(list_1, list_2, list_3): # Build the row: name + color + flattened third element row = [name, color] + flatten_element(third_item) writer.writerow(row)
What this does:
- Recursive Flattening: The
flatten_elementfunction takes any item (list or non-list) and returns a flat list. For nested lists, it recursively expands all sub-elements into individual values. - Row Construction: For each trio of elements (from
list_1,list_2,list_3), we combine the name, color, and the flattened version of the third item into a single flat list. - CSV Writing: The
writerowmethod then writes this flat list, where each element gets its own column.
Example Output CSV:
The resulting output.csv will look like this (columns separated by commas):
john,green,dog,cat peter,red,rabbit steve,blue,dog mike,purple, paul,orange,cat,mouse,elephant
This matches your desired outcome where every nested element occupies its own column.
内容的提问来源于stack exchange,提问作者magic10
相关产品推荐
相关产品推荐

