Python:将列表写入csv,将第一行转换为列

时间:2016-10-03 12:00:37

标签: python csv transpose

使用python,我将数据存储在列表中:

a = [['a', 'b', 'c'], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

我想将此列表写入csv,如下所示:

a, 1, 2, 3, 4
b, 5, 6, 7, 8
c, 9, 10, 11, 12

这是我在阅读了许多其他转置问题后想出的代码:

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])

这给了我:

a,1,5,9
b,2,6,10
c,3,7,11

所以它转换了整个列表(更不用说某些值甚至会丢失),但如上所示,我只希望第一行被转置。我只是不知道从哪里开始。

感谢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()

2 个答案:

答案 0 :(得分:0)

可能是这样的:

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>

答案 1 :(得分:0)

您需要拉出第一个子列表 zip ,其余部分在合并到一个列表后使用 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))