1

I have say three lists, and one of them is nested like so:

a = [1, 2, 3, 4]
b = ["abc", "def", "dec", "erf"]
c = [[5, 6, 7], [8, 9, 10], [11, 12, 13.3], [14, 15, 16]]

I would like a CSV file output of it which looks like this:

1,abc,5,6,7
2,def,8,9,10
3,erf,11,12,13.3
...

I tried zipping them and writing to a CSV file like so:

with open('filer.csv', "w") as f:
    writer = csv.writer(f)
    for row in zip(a, b, c):
        writer.writerow(row)

but the output has these stupid brackets like so:

1,abc,"[5,6,7]"
2,def,"[8,9,10]"
3,erf,"[11,12,13.3]"
...

but I want them without brackets and without the quotes like so:

1,abc,5,6,7
2,def,8,9,10
3,erf,11,12,13.3
...

:(

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
JohnJ
  • 6,736
  • 13
  • 49
  • 82

1 Answers1

5

Use:

with open('filer.csv', "w") as f:
    writer = csv.writer(f)
    for ai, bi, ci in zip(a, b, c):
        writer.writerow([ai, bi, *ci])

Output

1,abc,5,6,7
2,def,8,9,10
3,dec,11,12,13.3
4,erf,14,15,16

As you said you have nested list, so you need to flatten the list, the expression [ai, bi, *ci] flattens it.

The reason that you get the brackets is that writerow is (probably) applying the function str for each element of the iterable passed to it. And the string representation of a list includes the brackets, for example:

In[3]: str([1, 2, 3])
Out[3]: '[1, 2, 3]'
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76