如何在Python中创建多个(但单独的)空列表? [英] How to create multiple (but individual) empty lists in Python?

查看:1659
本文介绍了如何在Python中创建多个(但单独的)空列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个脚本,该脚本在某一时刻生成一堆空列表,并应用具有以下结构的代码:

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

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

产生输出:

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                  

在这里,我试图复制"A,B,C,D = [],[],[],[]",但显然不是这样.

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

我也尝试过:

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

但是最后,它只产生一个列表调用"field".

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

所以,这就是我需要的列表.我将从csv中读取信息,并将从每一行提取的数据添加到列表中.如果生成列表列表",我是否仍可以分别调用每个列表以将内容附加到列表上?

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]))

推荐答案

您正在使事情变得过于复杂.只需使用列表或字典即可:

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

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

然后根据需要引用fields['A']等,或遍历结构以依次处理每个对象.

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

这篇关于如何在Python中创建多个(但单独的)空列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆