Home > database >  List in list concatenation in python
List in list concatenation in python

Time:03-08

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 .

CodePudding user response:

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.

CodePudding user response:

You can use the zip builtin:

>>> list(zip(*lst))
[('cp1', 'ac1', '12/12/2020'), ('cp2', 'ac2', '12/12/2020')]

This will work with lists of any size.

CodePudding user response:

I think this is the code you need:

lst = [['cp1', 'cp2'], ['ac1', 'ac2'], ['12/12/2020', '12/12/2020']]
output = ""
for inner_list in lst:
    output  = inner_list[0]   ";"
output = output[:len(output) - 2]   "\n\n"
for inner_list in lst:
    output  = inner_list[1]   ";"
output = output[:len(output) - 2]
print(output)
  • Related