简体   繁体   English

如何在python中将列表写入CSV?

[英]How do I write lists into CSV in python?

I have the following list in Python.我在 Python 中有以下列表。

[('a1',
[('b', 1),
 ('c', 2),
 ('d', 3),
 ('e', 4),
 ('f', 5),
 ('g', 6]),

('a2',
[('c', 7),
 ('f', 8),
 ('g', 9),
 ('b', 1),
 ('e', 2),
 ('d', 3)])]

I would like to save the list as the following format in csv:我想在 csv 中将列表保存为以下格式:

a1      a2
b  1    c  7
c  2    f  8
d  3    g  9
e  4    b  1
f  5    e  2
g  6    d  3

The csv format is quite simple. csv 格式非常简单。

To start to know how to that, just create a csv file with the output you want, and open it with any text editor, you will obtain:要开始了解如何做到这一点,只需使用您想要的输出创建一个 csv 文件,并使用任何文本编辑器打开它,您将获得:

a1,,a2,
b,1,c,7
c,2,f,8
d,3,g,9
e,4,b,1
f,5,e,2
g,6,d,3

So here is the code you need, but should have at least to obtain alone.所以这里是你需要的代码,但至少应该有单独获得。

input_list = [('a1', [('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6)]), ('a2', [('c', 7), ('f', 8), ('g', 9), ('b', 1), ('e', 2), ('d', 3)])]

with open("my_file.csv", 'w') as f:
    first_line = [x[0] + ',' for x in input_list]
    f.write(",".join(first_line) + "\n")
    for x,y in zip(input_list[0][1], input_list[1][1]):
         k1, v1 = x
         k2, v2 = y
         f.write("{k1},{v1},{k2},{v2}\n".format(k1=k1, v1=v1, k2=k2, v2=v2))

An other solution is to use the csv module .另一种解决方案是使用csv 模块 And there are some examples in the doc.文档中有一些示例。

This should get you started:这应该让你开始:

>>> a = [('b', 1), ('c', 2)]
>>> b = [('c', 7), ('f', 8)]
>>>
>>> for x,y in zip(a,b):
...     k1, v1 = x
...     k2, v2 = y
...     print("{k1} {v1} {k2} {v2}".format(k1=k1, v1=v1, k2=k2, v2=v2))
...
b 1 c 7
c 2 f 8

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

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