You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将多列表合并后的嵌套元素拆分写入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:

  1. Recursive Flattening: The flatten_element function takes any item (list or non-list) and returns a flat list. For nested lists, it recursively expands all sub-elements into individual values.
  2. 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.
  3. CSV Writing: The writerow method 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:04:59