首页 > 解决方案 > 将数据列表从 python 导入 csv 的问题

问题描述

我刚刚开始使用 python,在将数据列表从 python 导出到 csv 时遇到了一些问题。

我有一些值数组,每个值对应一个特定的时间。我想要的是在 csv 上复制这些数组(都具有相同的长度),以便每一行呈现该特定时刻的所有变量的值。我写的是:

with open ('Risultati.csv', 'w', newline='' ) as f:
    thewriter=csv.writer(f)
    
    thewriter.writerow(['x','y','z','w'])
    for i in range(0,len(x)):
        thewriter.writerow(['x[%i]', 'y[%i]','z[%i]','w[%i]'])

但在我在每一行中获得的 csv 中是x[%i] y[%i] z[%i] w[%i]. 我还希望每个值列表都与标题对齐,就像在 Excel 表格中一样。

我希望我说清楚了。先感谢您。

标签: pythoncsvwriter

解决方案


以下情况如何:

import csv
import random

x = random.sample(range(10, 30), 5)
y = random.sample(range(10, 30), 5)
z = random.sample(range(10, 30), 5)
w = random.sample(range(10, 30), 5)

with open ('out.csv', 'w', newline='' ) as f:
    thewriter=csv.writer(f)

    thewriter.writerow(['x','y','z','w'])
    for i in range(0,len(x)):
        thewriter.writerow([x[i], y[i], z[i], w[i]])

给你:

$ python3 ./test.py
$ cat ./out.csv
x,y,z,w
18,23,17,25
23,27,16,26
15,18,28,10
12,15,23,18
26,29,21,27

我强烈建议您阅读有关 python 列表的教程!那里有很多,例如这个


推荐阅读