Home > Blockchain >  Assemble multiple lists into a single list through a loop
Assemble multiple lists into a single list through a loop

Time:02-10

As part of an application reading Csv files made using tkinder and the tksheet library, I would have liked to ensure that each of the lines retrieved from my spreadsheet and individually transformed into a list could be grouped into a single and unique comma separated list.

I currently have the following code:

with open('my_csv_file.csv') as csvfile:
     reader = csv.reader(csvfile, delimiter=';')
            
     for row in reader:
         if row != '' and row[0].isdigit():
            liste = [row[0], row[1], row[2], row[3], row[4]]
            print(liste)

Output :

['AAA', 'AAA', 'AAA', 'AAA', 'AAA']
['BBB', 'BBB', 'BBB', 'BBB', 'BBB']
['CCC', 'CCC', 'CCC', 'CCC', 'CCC']

What I want:

[['AAA', 'AAA', 'AAA', 'AAA', 'AAA'],
['BBB', 'BBB', 'BBB', 'BBB', 'BBB'],
['CCC', 'CCC', 'CCC', 'CCC', 'CCC']]

CodePudding user response:

Append to the top list to make your nested list.

lst = []

with open('my_csv_file.csv') as csvfile:
     reader = csv.reader(csvfile, delimiter=';')
            
     for row in reader:
         if row != '' and row[0].isdigit():
            lst.append([row[0], row[1], row[2], row[3], row[4]])

print(lst)

CodePudding user response:

you can add list and append list in the list with list =

with open('my_csv_file.csv') as csvfile:
     res = []
     reader = csv.reader(csvfile, delimiter=';')
            
     for row in reader:
         if row != '' and row[0].isdigit():
            res  = [[row[0], row[1], row[2], row[3], row[4]]]
            

or you can use append

with open('my_csv_file.csv') as csvfile:
     res = []
     reader = csv.reader(csvfile, delimiter=';')
            
     for row in reader:
         if row != '' and row[0].isdigit():
            res.append([row[0], row[1], row[2], row[3], row[4]])
            
  • Related