How to create multiple (but separate) empty lists in Python?

I wrote a script that at some point creates empty empty lists using code with a structure:

A,B,C,D=[],[],[],[] 

which produces the conclusion:

 A=[] B=[] C=[] D=[] 

As of now, I have to manually change the letters every time I use a different data set as input. I want to be able to automate this. I thought about it:

 FieldList=[A,B,C,D] bracket=[] [[0]for field in FieldList] for field in FieldList: bracket=bracket+["[]"] FieldList=bracket 

Here I tried to replicate "A, B, C, D = [], [], [], []", but obviously not how it works.

I also tried:

 FieldList=[A,B,C,D] bracket=[] [[0]for field in FieldList] for field in FieldList: field=[] 

But in the end, it simply gives out one word "field" of the list.

#

So, for this I need lists. I will read the information from csv and add the data that I extract from each row to the lists. If you create a “list of lists”, can I still call each one separately to add material to them?

 A,B,C,D=[],[],[],[] with open(csvPath+TheFile, 'rb') as csvfile: #Open the csv table r = csv.reader(csvfile, delimiter=';') #Create an iterator with all the rows of the csv file, indicating the delimiter between columns for i,row in enumerate(r): #For each row in the csv if i > 0: #Skip header A.append(float(row[0])) #Extract the information and append it to each corresponding list B.append(float(row[1])) C.append(format(row[2])) D.append(format(row[3])) 
+4
source share
4 answers

You exaggerate things. Just use a list or dictionary:

 fields = {key: [] for key in 'ABCD'} 

then refer to fields['A'] , etc. as needed or loop the structure to process each one in turn.

+9
source
 dict((k, []) for k in ['A','B','C','D']) 
+1
source

According to your usage example, you really want zip() :

In this example, note that csv.reader() basically splits the file into form data:

 [ ["a1", "b1", "c1", "d1"], ["a2", "b2", "c2", "d2"], ..., ["an", "bn", "cn", "dn"] ] 

Example:

 table = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ] #How to transpose the data into columns??? Easy! columns = zip(*table) 

Now you have the columns variable of the form:

 columns = [ [1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12] ] 

Ok, so apply this to the csv file:

 with open("mycsv.csv", "rb") as infile: reader = csv.reader(infile, delimiter=";") next(reader, None) #skip the header columns = zip(*reader) 

What is it!

Note. In this example, we assume that "mycsv.csv" has the correct number of columns in each row. You may need to perform a check to make sure that all lines are "full".

0
source

Check the accepted answer here . (Respond to click or not to click)

 >>> obj = {} >>> for i in range(1, 21): ... obj['l'+str(i)] = [] ... >>>obj {'l18': [], 'l19': [], 'l20': [], 'l14': [], 'l15': [], 'l16': [], 'l17': [], 'l10': [], 'l11': [], 'l12': [], 'l13': [], 'l6': [], 'l7': [], 'l4': [], 'l5': [], 'l2': [], 'l3': [], 'l1': [], 'l8': [], 'l9': []} >>> 
0
source

All Articles