Home > Blockchain >  write to csv file two lists separated by tab error
write to csv file two lists separated by tab error

Time:06-07

I have to lists

a = [1,2,3,4]
b = [[2,3,4,5],[2,4,3,9], [9,4,6,8], [7,3,8,5]]

I have written it to a csv file with delimiter as tab. Now I don't want to have the nested list as [2,3,4,5] but only the element 2,3,4,5. I don't know how to get rid of the the list brackets.

Here is my code:

with open('output.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
wr = csv.writer(myfile, delimiter='\t')
wr.writerows(zip(a,b))

output of my code:

1   [2, 3, 4, 5]
2   [2, 4, 3, 9]
3   [9, 4, 6, 8]
4   [7, 3, 8, 5]

But I want to have

1   2, 3, 4, 5
2   2, 4, 3, 9
3   9, 4, 6, 8
4   7, 3, 8, 5

Thanks!

CodePudding user response:

The second column is the default str() of a list. You can format the second column as a custom string to get what you want:

import csv

a = [1,2,3,4]
b = [[2,3,4,5],[2,4,3,9], [9,4,6,8], [7,3,8,5]]

with open('output.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
    wr = csv.writer(myfile, delimiter='\t')
    for col1,col2 in zip(a, b):
        str_col2 = ', '.join([str(n) for n in col2])
        wr.writerow([col1, str_col2])

Output:

1       2, 3, 4, 5
2       2, 4, 3, 9
3       9, 4, 6, 8
4       7, 3, 8, 5

CodePudding user response:

Not sure if you're able to flatten an n-dimensional list with only zip. I'd do something like the following, to flatten every single output line of zip(a, b):

flattened = []
for ab in zip(a, b):
    flattened.append([ab[0]]   ab[1])

wr.writerows(flattened)
  • Related