我有三个列表a
,b
和c
,我想将这些列表写为csv文件。我遇到了麻烦(因为data
将这些作为行)并且还编写了csv。这就是我所拥有的。
import csv
my_output=open('myfile.csv','wb')
mywriter=csv.writer(csv_out)
a=[1,3,5,7]
b=[2,4,6,8]
c=[0,0,0,0]
data=[a,b,c]
for item in data:
mywriter.writerow(item)
my_output.close()
答案 0 :(得分:0)
Excel将数据存储在Row-major order。
中你必须先解决问题:
a = [1,3,5,7]
b = [2,4,6,8]
c = [0,0,0,0]
data = [a,b,c]
for i in range(len(data[0])):
for j in range(len(data)):
print data[j][i],
print ''
<强>输出:强>
1 2 0
3 4 0
5 6 0
7 8 0
import csv
my_output = open('myfile.csv', 'wb')
mywriter = csv.writer(my_output)
a = [1,3,5,7]
b = [2,4,6,8]
c = [0,0,0,0]
data = [a,b,c]
for i in range(len(data[0])):
row = [data[j][i] for j in range(len(data))]
mywriter.writerow(row)
my_output.close()
import csv
my_output = open('myfile.csv', 'wb')
mywriter = csv.writer(my_output)
a = [1,3,5,7]
b = [2,4,6,8]
c = [0,0,0,0]
data = [a,b,c]
for row in zip(*data):
mywriter.writerow(row)
my_output.close()
有关此内置功能的信息,请参阅zip([iterable, ...])
。
答案 1 :(得分:0)
无需创建变量data
。使用内置功能zip。它使迭代器聚合来自每个迭代的元素。
for item in zip(a, b, c):
mywriter.writerow(item)