匹配后追加到列表

时间:2018-09-10 10:53:00

标签: python

在继承某人的作品后,我陷入了一个相当随机的问题。

目前有2个CSV文件正在导入python程序 1个包含数字 1个包含模式和站点代码

当前,他的程序将正确导入两个CSV 并检查“数字中是否包含模式”,如果是,它将先打印与之匹配的模式编号,再打印站点代码。

问题实际上是他想将每个匹配项附加到以他也静态创建的站点代码命名的列表中。

经过大量的搜索之后,似乎可以选择globals()来获得所需的行为

即:

x = Range[0]
globals()[x].append(DDI)

其中Range [0]是站点代码

我似乎遇到的问题是,尽管比较行在打印时工作正常,但所有数组的结果都相同

完整的上下文代码:

with open('NumPlan.csv', 'r') as f:
    mylist = []
    AEDUB = ATVIE = ATVZR = BEANT = BEBRS = BEBRU = BEMPL = CHBAS = CHLAS = CHZUR = CHWRO = CZOPA = CZPPA = DEBER = DEBSS = DEBRS = DECOL = DEDUS = DEESS = DEFBA = DEFFM = DEFRA = DEHAM = DEMUN = DENUR = DESTU = DKAAR = DKALB = DKCOP = ESBCN = ESMAD = ESMDD = ESPAL = ESVAL = FIHEL = FRBAG = FRBOR = FRLIL = FRLYN = FRMAR = FRMON = FRPRO = FRRHB = FRTOU = GBABE = GBAZT = GBBEL = GBBIR = GBBRI = GBCOL = GBEDI = GBGPH = GBGSH = GBLBS = GBLEE = GBLIV = GBLHH = GBLON = GBLWR = GBMAN = GBNOR = GBPAR = GBSMC = GBSOU = GBTRA = GBTHE = GBXWH = HUBUD = HUGUB = IEDBL = ITMIL = ITMOD = ITMVP = ITROM = ITTUR = ITMIG = LULGI = LULUX = NLAMS = NLUTR = NLDEN = NLRIK = NLROT = NLSCH = NODRO = PLWRO = PLART = PLWAA = PLWKS = PTLIS = ROBUC = RUMOS = SKBRA = SKZAM = SESTG = SESTO = SESOL = TRIST = []
    with open('Ranges.csv', 'r') as R:

     currentDDI = []
     ranges = []
     for line in f:
         li = line.split(",")
         for each in li:
             if "\\" in each:
                 currentDDI.append(each.strip())

     for line2 in R:
         Range = line2.split(",")

         for DDI in currentDDI:
             if Range[1].strip() in DDI.strip():
                 x = Range[0]
                 globals()[x].append(DDI)

     print(GBSMC)

1 个答案:

答案 0 :(得分:1)

您已将单个列表对象分配给一系列名称:

AEDUB = ATVIE = ATVZR = BEANT = ... = SESOL = TRIST = []

所有这些名称现在都引用同一列表对象,而不是单独的对象。 Python names are just labels or name tags,并且类似列表对象的值可以具有多个此类标记:

>>> AEDUB = ATVIE = ATVZR = []  # 3 names for the same list
>>> AEDUB.append('foo')  # append to the list via one name
>>> ATVIE  # and the same change is visible via another other name
['foo']
>>> ATVZR  # and another
['foo']
>>> ATVIE is ATVZR is AEDUB  # all names refer to the same object?
True

您必须为每个名称分别键入分配:

AEDUB = []
ATVIE = []
ATVZR = []
BEANT = []
... 
SESOL = []
TRIST = []

但是,您确实想使用globals() 避免并使用单独的命名列表。请改用字典:

site_codes = {}

site_codes.setdefault(Range[0], []).append(DOI)

dict.setdefault()方法在此处获取一个密钥(Range[0]),如果该密钥已经存在,则返回该密钥的值。如果缺少,则第二个参数用于首先设置字典中的值。因此,如果Range[0]尚未在字典中,则它将被设置为空列表,否则将返回现有列表。然后,.append()调用将追加到Range[0]的列表中。

请注意,您不必真正键入所有这些名称!

然后,您可以在其他地方使用site_codes['AEDUB']等来引用这些列表,或者仅使用for site_code in site_codes:访问名称序列或使用for site_code, values in site_codes.values():访问名称和列表,等等。这比使用全局名称要实际得多。