gpt4 book ai didi

python - 按列写 csv

转载 作者:行者123 更新时间:2023-11-28 22:13:43 26 4
gpt4 key购买 nike

我有一个列表列表示例:list_of_lists = [['name1', 'number1', 'comment1'], ['name2', 'number2', 'comment2'], ['name3', 'number3', 'comment3']]

我想将它们写入一个如下所示的 csv 文件:

NAME  NUMBER  COMMENT
name1 number1 comment1
name2 number2 comment2
name3 number3 comment3

我试过:

rows = zip(*list_of_lists)
import csv
with open('new.csv', "w") as f:
writer = csv.writer(f)
for row in rows:
writer.writerow(row)

但是写成:

name1    name2   name3
number1 number2 comment2
comment1 number3 comment3

如果我使用 rows = zip(list_of_lists) 而不是 rows = zip(*list_of_lists),我会在 csv 中以字符串形式获取所有数据:

"name1, number1, comment1"
"name2, number2, comment2"
"name3, number3, comment3"

如何获得想要的结果?

最佳答案

您可以直接使用它们。

例如:

import csv

list_of_lists = [['name1', 'number1', 'comment1'], ['name2', 'number2', 'comment2'], ['name3', 'number3', 'comment3']]

with open(filename, "w") as f:
writer = csv.writer(f)
writer.writerow(["NAME", "NUMBER", "COMMENT"])
for row in list_of_lists:
writer.writerow(row)

关于python - 按列写 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53762305/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com