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

如何在Python中使用循环将多组列表数据导出至CSV文件

Exporting List Data to CSV in Loops (Fixing Your Code)

Hey! Let's sort out your CSV export code. I notice you're trying to write paired data from lists X and Y into a CSV, with each loop iteration handling a set of columns. Let's first break down the issues in your original snippet:

  • Overwriting the file every time: Using open(..., "w") inside the loop means each iteration replaces the entire file—you'll only end up with the last set of data.
  • Incorrect variable access: Your loop variable x is an integer (0 and 1 from range(0,2,1)), so x[0] throws an error. You meant to reference X[x] instead!
  • Missing paired data: Your current code only writes values from one list, but you want to pair X[x] with Y[x] as columns.

Here's a revised version that does exactly what you're asking—writing pairs from X[0] & Y[0] (as two columns) first, then X[1] & Y[1]:

import csv

X = ([1,2,3], [7,8,9])
Y = ([4,5,6], [3,4,5])
csv_path = "C:/Temp/aaa.csv"

# Open the file once (use 'a' instead of 'w' to append to an existing file)
with open(csv_path, "w", newline='') as output_file:
    writer = csv.writer(output_file, lineterminator='\n')
    
    # Loop through each index in X and Y
    for i in range(len(X)):
        # Get the corresponding lists from X and Y
        current_x = X[i]
        current_y = Y[i]
        
        # Write each paired value as a row (two columns)
        for x_val, y_val in zip(current_x, current_y):
            writer.writerow([x_val, y_val])

Quick Explanations:

  • Single file open: Opening the file outside the loop prevents overwriting. Use 'a' instead of 'w' if you need to add to an existing CSV instead of creating a new one.
  • Zipping lists: zip(current_x, current_y) matches up elements from the two lists (e.g., 1 with 4, 2 with 5), so each row gets two columns of related data.
  • Cleaner iteration: Using range(len(X)) ensures we loop through every pair of lists in X and Y, even if you add more later.

If you wanted to structure the CSV differently (like adding headers, or writing each group as separate sections), just let me know—I can tweak this further!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:33:42