python - 将数据列表从 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 表格中一样。
我希望我说清楚了。先感谢您。
解决方案
以下情况如何:
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 列表的教程!那里有很多,例如这个
推荐阅读
- vba - 为具有不同数据量的列自动生成频率和直方图
- scheme - 试图编写一个返回另一个函数的函数,但 Racket 说我的 lambda 不是函数定义?
- javascript - 我如何使用 JS 将图像链接到锚标记?(我正在使用 cloud firestore 工作的功能,管理员的新游戏添加选项)
- java - 减法给出奇怪的结果 [Java]
- asp.net - 无法在 Web api 配置中设置自定义合同解析器
- postgresql - 将 PostgreSQL Alpine 映像切换到 Debian 并从 12.3 升级到 12.6 后出现“信号 11:分段错误”错误
- javascript - 我们应该检查前端 JavaScript 代码的漏洞吗?
- spring-boot - 在 Spring Boot 中使用 Google 登录后重定向到页面用户
- javascript - Node.js 在后端和前端之间共享代码
- go - 我们如何管理 Rest API 查询参数中的“#”