Python,转置列表并写入CSV文件

标签 python list csv

我需要使用 python 写入一个 csv 文件,每个迭代器项目都应该在一个新行中开始。 所以我使用的分隔符是“\n”。 每个列表都写完后,下一个列表应该从下一个单元格开始写。 如下所示:

 lol = [[1,2,3],[4,5,6]]

csv 会是这样的:

1 4
2 5
3 6

我尝试过的:

file = open("test.csv", "wb")
fileWriter = csv.writer(file , delimiter='\n',quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamWriter.writerow([1,2,3])
spamWriter = csv.writer(file , delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamWriter.writerow([4,5,6])
file.close()

结果如下:

 1
 2
 3
 4 5 6

使用 csv 模块如何获得如下输出:

 1 4 
 2 5
 3 6

这里的空格在csv文件中表示逗号。

谢谢。

最佳答案

如果不使用 zip,您可以这样做:

import csv

lol = [[1,2,3],[4,5,6],[7,8,9]]
item_length = len(lol[0])

with open('test.csv', 'wb') as test_file:
  file_writer = csv.writer(test_file)
  for i in range(item_length):
    file_writer.writerow([x[i] for x in lol])

这将输出到 test.csv 中:

1,4,7
2,5,8
3,6,9

关于Python,转置列表并写入CSV文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10573915/

相关文章:

python - 创建满足一个条件的多个列表 Python 3.6

python - 将 Pandas 数据框保存到具有不同列名的 sqlite 中?

python - 全局无法正常工作 [Python]

c++ - STL列表中结构的自动初始化

postgresql - 带引号的 NULL 值使 PostgreSQL COPY 命令失败

csv - LibreOffice Calc : How to open CSV with numbers as text?

r - write.csv() 极其意外的行为

python - 列表理解和循环之间的区别

Javascript - 点击列表元素加载HTML页面动画

list - Haskell - 无限列表 -