简体   繁体   English

Python将两个列表写到csv中,经过扁平化,并带有列标题

[英]Python write two lists to csv, flattened, and with a column header

I have two list of lists: 我有两个清单清单:

A = [[1,2,3,4,5,6], [9,2,4,5,3,2]]
B = [[12,5,6,7,8,6], [12,1,3,4,1,2]]

I would like to write the values in these lists to csv file in following way. 我想以下列方式将这些列表中的值写入csv文件。

import csv    

writer = csv.writer(open('randnums.csv','w'))

for row in A,B:
    writer.writerow(row)

Where the result is one row with the items from A[0] and B[0] (and so on) with a header like this: 其中结果是一行,其中包含A [0]和B [0](以此类推)的项目,标题如下:

A,B,C,D,E,F,G,H,J,K,L,M
1,2,3,4,5,6,12,5,6,7,8,6
9,2,4,5,3,2,12,1,3,4,1,2
>>> import csv, string
>>> A = [[1,2,3,4,5,6], [9,2,4,5,3,2]]
>>> B = [[12,5,6,7,8,6], [12,1,3,4,1,2]]
>>> with open('randnums.csv','w') as f:
    w = csv.writer(f)
    w.writerow(string.uppercase[:len(A[0] + B[0])])
    for x, y in zip(A, B):
        w.writerow(x + y)


>>> with open('randnums.csv') as f:
    print f.read()


A,B,C,D,E,F,G,H,I,J,K,L
1,2,3,4,5,6,12,5,6,7,8,6
9,2,4,5,3,2,12,1,3,4,1,2
In [114]: for row in zip([['A','B','C','D','E','F']] + A, [['G','H','J','K','L','M']] + B):
     ...:     new_row = row[0] + row[1]
     ...:     print new_row
     ...:     #writer.writerrow(new_row)
     ...:     
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M']
[1, 2, 3, 4, 5, 6, 12, 5, 6, 7, 8, 6]
[9, 2, 4, 5, 3, 2, 12, 1, 3, 4, 1, 2]

I think you are looking for the zip() function to iterate two lists at the same time. 我认为您正在寻找zip()函数来同时迭代两个列表。

Here is how you could use it : 这是您如何使用它:

import csv    
import string

A = [[1,2,3,4,5,6], [9,2,4,5,3,2]]
B = [[12,5,6,7,8,6], [12,1,3,4,1,2]]

writer = csv.writer(open('randnums.csv','w'))

writer.writerow("".join(string.ascii_uppercase[:13]))

for a, b in zip(A,B):
    str_list = [str(i) for i in a+b]
    line = "".join(str_list)
    writer.writerow(line)

It gives you a file randnums.csv with : 它为您提供randnums.csv文件, randnums.csv包含:

A,B,C,D,E,F,G,H,I,J,K,L,M
1,2,3,4,5,6,1,2,5,6,7,8,6
9,2,4,5,3,2,1,2,1,3,4,1,2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM