Python,转置列表并写入CSV文件 [英] Python, transposing a list and writing to a CSV file

查看:1950
本文介绍了Python,转置列表并写入CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用python写入一个csv文件,每个迭代器项目应该在一个新行开始。
所以我使用的分隔符是\\\

每个列表写入后,下一个列表应从下一个单元格写入。
如下:

I need to write into a csv file using python and each iterator item should start in a new line. So delimiter I am using is "\n". After each list has been written,next list should write from next cell. like below:

 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模块如何获得如下输出:

Using csv module how can I get output like below:

 1 4 
 2 5
 3 6

这里的空格是指csv文件中的逗号。

here space means comma in a csv file.

感谢。

推荐答案

不使用zip,可以这样做:

Without using zip, you could do this:

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:

This will output into test.csv:

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

这篇关于Python,转置列表并写入CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆