4

I wrote a script that at one point generates a bunch of empty lists applying a code with the structure:

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

which produces the output:

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

The way it is right now, I have to manually modify the letters each time I use a different dataset as an input. I want to be able to automatize that. I thought about doing this:

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

Here I was trying to replicate " A,B,C,D=[],[],[],[]", but evidently that's not how it works.

I also tried:

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

But at the end it just produces a single list call "field".

#

So, this is what I need the lists for. I will be reading information from a csv and adding the data I'm extracting from each row to the lists. If generate a "list of lists", can I still call each of them individually to append stuff 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]))
Noebyus
  • 65
  • 1
  • 7
  • 5
    Why not have a single, multi-dimensional list, instead of all these separate lists? – Robert Harvey Apr 11 '13 at 16:15
  • 2
    I think you want a list of lists or a dictionary of lists. – NPE Apr 11 '13 at 16:15
  • 1
    I THINK a list of lists wouldn't work for me because of how I have to use each element later. Let me show you how the rest of my code looks like so you can judge for yourself. – Noebyus Apr 11 '13 at 16:18
  • 1
    You have second choice `>> a, b, c, d = ([],)*4` but all reference to same `[]` – Grijesh Chauhan Apr 11 '13 at 16:21
  • Based on your update, your real question is "How do I get csv data in columns instead of rows?". – Joel Cornett Apr 11 '13 at 16:35
  • weeeell, not really. I mean, I have already written a code that works for that. I just wanted to change the tiny bit of code regarding setting up blank lists so I can make the overall code more flexible. I wouldn't want to re-write everything. Martijn Pieters solution works just fine for what I need right now. Thanks all for your attention! – Noebyus Apr 11 '13 at 17:35

4 Answers4

9

You are overcomplicating things. Just use a list or dictionary:

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

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1
dict((k, []) for k in ['A','B','C','D'])
Yarkee
  • 9,086
  • 5
  • 28
  • 29
1

Based on your usage example, what you actually want is zip():

For this example, note that csv.reader() basically breaks the file up into data of the form:

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

The 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 a variable, columns, of the form:

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

Okay so let's apply this to a csv file:

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

That's it!

Note: For this example, we are assuming that "mycsv.csv" has the correct number of columns in every row. You may need to implement a check to make sure that all of the rows are "filled in".

Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
0

Check the accepted answer here. (Answer by 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': []}
>>> 
Community
  • 1
  • 1
MycrofD
  • 231
  • 1
  • 6
  • 17