[英]Python: write list to csv, transposing the first row into a column
Using python, I have data stored in a list: 使用python,我将数据存储在列表中:
a = [['a', 'b', 'c'], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
I want to write this list to a csv that looks like the following: 我想将此列表写入如下所示的csv:
a, 1, 2, 3, 4
b, 5, 6, 7, 8
c, 9, 10, 11, 12
This is the code I came up with after reading lots of other transposing problems: 这是我在阅读许多其他转置问题之后想到的代码:
length = len(a[0])
with open('test.csv', 'w') as test_file:
file_writer = csv.writer(test_file)
for i in range(length):
file_writer.writerow([x[i] for x in a])
Which gives me: 这给了我:
a,1,5,9
b,2,6,10
c,3,7,11
So it transposes the entire list (not to mention that some values even get lose), but as shown above, I only want the first row to be transposed. 因此,它转置了整个列表(更不用说有些值甚至会丢失),但是如上所述,我只希望第一行被转置。 I just don't know where to even get my hand on. 我只是不知道该在哪儿找到我的手。
Thanks to Nf4r, I came up with the following -- may look awkward, but works :-) 多亏了Nf4r,我提出了以下建议-看起来很尴尬,但效果不错:-)
a = [['a', 'b', 'c'], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
f = open('test.csv', 'a')
for header, data in zip(a[0], a[1:]):
result = "{header}, {data}".format(header = header,
data = ', '.join((str(n) for n in data)))
f.write(result)
f.write('\n')
f.close()
Maybe something like: 也许像:
a = [['a', 'b', 'c'], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
for header, data in zip(a[0], a[1:]):
result = "{header}, {data}".format(header= header,
data= ', '.join((str(n) for n in data)))
print(result)
a, 1, 2, 3, 4
b, 5, 6, 7, 8
c, 9, 10, 11, 12
<do what u want with it>
You just need to pull the first sublist and zip with the remainder then use writerows after combining into a single list: 您只需要拉出第一个子 列表并压缩其余部分,然后在合并为一个列表后使用writerows :
a = [['a', 'b', 'c'], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
import csv
with open('test.csv', 'w') as test_file:
file_writer = csv.writer(test_file)
it = iter(a)
col_1 = next(it)
file_writer.writerows([a] + b for a,b in zip(col_1, it))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.