Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List in list concatenation in python

lst = [['cp1', 'cp2'], ['ac1', 'ac2'], ['12/12/2020', '12/12/2020']]

i want to write in a csv file as below

cp1;ac1;12/12/2020

cp2,ac2,12/12/2020

but the length of lst is not fixed it is dynamic (here it is 3 but can be N) . how ever lists in lst will have same number of element (in above example 2 ) .

can anybody give me suggestion . I am new in python .

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use zip and csv module:

data  = [['cp1', 'cp2'], ['ac1', 'ac2'], ['12/12/2020', '12/12/2020']]

import csv

with open ("test.csv","w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(zip(*data))


with open("test.csv") as r:
    print(r.read())

Output:

cp1,ac1,12/12/2020
cp2,ac2,12/12/2020

This will work as long as you make sure your inner lists all have the same lenght. If one is shorter all lists will be shortened to that lenght. Use itertools.zip_longest to avoid that shortening.

See Writing a Python list of lists to a csv file if your lists are already formatted correctly and do not need to be transposed before writing.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading