列表中的Python输出列表在csv列表中

时间:2016-10-25 07:23:22

标签: python csv export-to-csv

data_set =[
['a1', ['b1','c1','d1'],'f1' 'g1'],
['a2', ['b2','c2','d2'],'f2' 'g2'],
['a3', ['b3','c3','d3'],'f3' 'g3']
]

header = ['a', 'b-c-d', 'f', 'g']

我想返回一个仅包含4个项目的csv。

each row = ['a1', ['b1','c1','d1'], 'f1', 'g1']

with open("output.csv", "w") as fp:
    a = csv.writer(fp, delimiter='\t')
    a.writerow(header)
    a.writerows(data_set)

1 个答案:

答案 0 :(得分:0)

在澄清时编辑:

我相信这就是你想要的:

In [18]: def flatten(item):
    ...:     if isinstance(item,list):
    ...:         return ", ".join(item)
    ...:     else:
    ...:         return item
    ...:     

In [19]: with open("output.csv", "w") as fp:
    ...:     a = csv.writer(fp, delimiter='\t')
    ...:     a.writerow(header)
    ...:     for row in data_set:
    ...:         a.writerow((flatten(r) for r in row))
    ...:         

In [20]: cat output.csv
a   b-c-d   f   g
a1  b1, c1, d1  f1  g1
a2  b2, c2, d2  f2  g2
a3  b3, c3, d3  f3  g3

原始答案:

如果我理解正确,你的意思是两件事中的一件,对我来说这两件事似乎都不是好主意:

In [6]: data_set =[
   ...: ['a1', ['b1','c1','d1'],'f1', 'g1'],
   ...: ['a2', ['b2','c2','d2'],'f2', 'g2'],
   ...: ['a3', ['b3','c3','d3'],'f3', 'g3']
   ...: ]

In [7]: with open("output.csv", "w") as fp:
   ...:     a = csv.writer(fp, delimiter='\t')
   ...:     a.writerow(header)
   ...:     for row in data_set:
   ...:         a.writerow((str(row),))
   ...:         

In [8]: cat output.csv
a   b-c-d   f   g
['a1', ['b1', 'c1', 'd1'], 'f1', 'g1']
['a2', ['b2', 'c2', 'd2'], 'f2', 'g2']
['a3', ['b3', 'c3', 'd3'], 'f3', 'g3']

或者你的意思是:

In [9]: with open("output.csv", "w") as fp:
   ...:     a = csv.writer(fp, delimiter='\t')
   ...:     a.writerow(header)
   ...:     for row in data_set:
   ...:         a.writerow((str(r) for r in row))
   ...:         
   ...:         

In [10]: cat output.csv
a   b-c-d   f   g
a1  ['b1', 'c1', 'd1']  f1  g1
a2  ['b2', 'c2', 'd2']  f2  g2
a3  ['b3', 'c3', 'd3']  f3  g3

In [11]: