简体   繁体   中英

How do I write lists into CSV in python?

I have the following list in 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:

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.

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:

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 . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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