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

:(

1
  • Perhaps c should use ','.join(c). So unpack the zip into individual varaibles. Commented Oct 20, 2021 at 14:31

1 Answer 1

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]'
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for solving this for me - I just spent 2 hours on this - I should really quit being a programmer! Thank you again.
@JohnJ Glad I could help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.