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

Python新手求助:如何将嵌套列表垂直数据转为水平CSV输出?

Fixing CSV Export for Nested List Data

Hey there! I get it, dealing with nested lists and CSV exports can be tricky when you're starting out. The issue here is that you need to transpose your data (swap rows and columns) before writing it to CSV, instead of dumping each sublist into a single cell. Let's break this down step by step.

Step 1: Transform Your Data

Your original data is structured as rows:

original_data = [['1','2','3'],['4','','6'],['7','8','9']]

You need to flip it so columns become rows, like this:

['1','4','7'], ['2','','8'], ['3','6','9']

In Python, the simplest way to transpose a list of lists is using zip(*original_data). This unpacks each sublist and pairs up elements at the same positions automatically.

Step 2: Write to CSV Correctly

Using Python's built-in csv module ensures empty values stay empty and the CSV is formatted properly (no extra brackets or unwanted quotes). Here's the full working code:

import csv

# Your extracted nested list from XPath
original_data = [['1','2','3'],['4','','6'],['7','8','9']]

# Transpose the data: turn columns into rows
transposed_data = zip(*original_data)

# Write the transposed data to a CSV file
with open('output.csv', 'w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    # Write each transposed row to the CSV
    writer.writerows(transposed_data)

What This Does:

  • zip(*original_data) takes your 3 rows and converts them into 3 columns (now treated as rows for the CSV).
  • csv.writer handles putting each element into its own cell—empty strings like '' will show up as blank cells in the CSV, which is exactly what you want.
  • The newline='' parameter prevents extra blank lines from appearing between rows on Windows.

Edge Case: Unequal Sublist Lengths

If your extracted data has sublists of different lengths, zip will stop at the shortest sublist. To fix this, use itertools.zip_longest to fill missing values with empty strings:

from itertools import zip_longest

transposed_data = zip_longest(*original_data, fillvalue='')

Why Your Original Approach Failed

Chances are you were writing the entire sublist as a single string (like str(sublist)) to each cell, which is why you saw ['1', '2', '3'] in one cell instead of three separate cells. By transposing and using csv.writer, we ensure every element gets its own proper cell.

内容的提问来源于stack exchange,提问作者emiwark

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:52:56