简体   繁体   中英

Write Python list of lists row wise to a csv file

I have a list like this

[[1.75], [4.75]]
[[2.5], [2.5]]
[[3.5], [3.5]]
[[4.0], [4.0]]

I want to write this to a csv file like

1.75, 4.75
2.5, 2.5
3.5, 3.5
4.0, 4.0

When I tried using writerows method of csv module it is saved as

1.75
4.75
2.5
2.5
3.5
3.5
4.0
4.0

You need to unpack each row into a flat list.

import csv

my_list = [
    [[1.75], [4.75]],
    [[2.5], [2.5]],
    [[3.5], [3.5]],
    [[4.0], [4.0]],
    ]

with open("my.csv", "w") as f:
    writer = csv.writer(f)

    for row in my_list:
        writer.writerow([l[0] for l in row])

Or if preferred, the for loop could be replaced with a generator expression so that you can use writerows as you are currently doing:

    writer.writerows([l[0] for l in row] for row in my_list)

Here is a possible solution:

import csv

lst = [[[1.75], [4.75]],
       [[2.5], [2.5]],
       [[3.5], [3.5]],
       [[4.0], [4.0]]]

with open('file.csv', 'w') as f:
    writer = csv.writer(f)
    w.writerows([[x[0] for x in lst] for line in lst])

Alternatively, you can flat your list by using itertools.chain :

from itertools import chain
...
w.writerows([list(chain(*line)) for line in lst])

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