Python: write set of lists (1 nested list) to csv file

Question:

I have a set of data with two lists. list_2 can have any number of nested lists in it (which is where my problem stems from).

list_1 = [2000.0, 2100.0, 2200.0]
list_2 = [[-1.86, 0.49, 1.36], [-1.29, 0.59, 1.62], [-.99, 0.19, 1.76]]

once in the csv file it should look like

2000    -1.86    -1.29    -.99
2100    0.49    0.59     0.19
2200    1.36     1.62     1.76

I have tried a few different ways of writing the file

    with open(file_name, 'w') as file:
        writer = csv.writer(file)
        writer.writerows(zip(list_1, list_2))

I’ve also tried zipping them before as see in this question

I’ve also tried separating the lists (in list_2) but that does not allow for any growth. I do not know the number of nested lists before running the application so it has to be able to grow.

writer.writerows(zip(list_1, list_2, list_3, list_4))  # does not allow for dynamic growth
Asked By: Luke

||

Answers:

You can do this with the * operator:

zip(list_1, *list_2)

This will create a list of lists where the first element of each sub list comes from list_1 and the remaining elements come from each of the lists in list_2.

Answered By: Code-Apprentice

if I get you right you don’t know how many lists you are going to have. But all of them will have the same size?

And you want them to be stored "vertically"?

I have the feeling a transpose
operation would help you very well.

import csv
import numpy

list_1 = [2000.0, 2100.0, 2200.0]
list_2 = [[-1.86, 0.49, 1.36], [-1.29, 0.59, 1.62], [-.99, 0.19, 1.76]]

list_3 = [list_1] + list_2
output_array = numpy.transpose(numpy.array(list_3))

with open(file_name, 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(output_array)
Answered By: Alexander Khomenko
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.