2016-05-18 89 views
2

我目前正在编写一些从文本文件中读取行的代码。该行被分成3个不同的段,第一段是用户ID。修改列表中包含的字典

例如,一条线是这样的:

11 490 5 

我有因为有用户一样多的元素,其中每个元素与用户对应的第五用户(例如exampleList[4]存储数据的列表)。

每个列表元素包含一个不确定长度的字典,其中键是该行的第二个段,该值是该行的第三个段。

如果在另一行中出现相同的用户ID,字典的长度(键值对的数量)会增加。这个想法是,当遇到具有相同用户ID的另一行时,来自该行的数据被附加到对应于该用户的列表元素的字典中。

例如,上述线路将被存储在这样的:

exampleList[10] = {490:5} 

,如果程序读取另一行是这样的:11 23 9

列表项将自动更新到这一点:

exampleList[10] = {490:5, 23:9} 

我的程序工作的方式是,它首先收集用户数量,然后创建一个像这样的列表:

exampleList = [{}] * numberOfUsers 

然后使用re.finditer提取行中的空白位置,然后通过基本字符串操作提取数字。

该部分完美工作,但我不确定如何更新列表中的字典,即将新的键值对添加到字典中。

我读过关于使用for循环here,但这不适用于我,因为它将它添加到单元格中的每个字典中,而不是仅将它附加到某个单元格中的字典中。

示例代码:

oFile = open("file.txt", encoding = "ISO-8859-1") 
    text = oFile.readlines() 
    cL = [{}] * numOfUsers #imported from another method 
    for line in text: 
     a = [m.start() for m in re.finditer('\t', line)] 
     userID = int(line[0:a[0]]) 
     uIDIndex = userID - 1 
     cL[uIDIndex].update({int(line[a[0]+1:a[1]]):int(line[a[1]+1:a[2]])}) 
    print(cL) 

file.txt: 
1 242 3 
3 302 3 
5 333 10 
1 666 9 

expected output: 
[{242:3 , 666:9},{},{302:3},{},{333:10}] 

actual output: 
[{242: 3, 333: 10, 302: 3, 666: 9}, {242: 3, 333: 10, 302: 3, 666: 9}, {242: 3, 333: 10, 302: 3, 666: 9}, {242: 3, 333: 10, 302: 3, 666: 9}, {242: 3, 333: 10, 302: 3, 666: 9}] 

出于某种原因,它填充与所有值的列表中的所有词典。

+0

请您分享一些您的代码。 –

+1

如果你想要一个字典列表,你为什么要创建一个列表清单? – TessellatingHeckler

+0

你可以加入一些固体样品和预期产量吗? –

回答

0

我不是很积极正确理解你的问题,但我能够得到你想要的输出。 请注意,此解决方案完全忽略列表中的第四个值

import re 
fileData = [] #data from file.txt parsed through regex 

with open("file.txt") as f: 
    for line in f: 
     regExp = re.match(r"(\d+)\s+(\d+)\s(\d+)", line) #extracts data from row in file 
     fileData.append((int(regExp.group(1)), int(regExp.group(2)), int(regExp.group(3)))) #make 2-d list of data 
maxIndex = max(fileData, key=lambda x: x[0])[0] #biggest index in the list (5 in this case) 

finaList = [] #the list where your output will be stored 
for i in range(1, maxIndex+1): #you example output showed a 1-indexed dict 
    thisDict = {} #start with empty dict 
    for item in fileData: 
     if item[0] == i: 
      thisDict[item[1]] = item[2] #for every item with same index as this dict, add new key-value to dict 
    finaList.append(thisDict) #add this dict to output list 

print(finaList) 
+0

完美!非常感谢你 - 如果我让问题难以理解,我不是最擅长沟通的。 – user132520

+0

我认为问题不是你的解释,我认为这只是一个复杂的问题,很难在文本中传达。但是,对我来说理解这个问题是99%的战斗,编码解决方案并不复杂 – Keatinge

0

您可以通过索引访问字典。这里有一个简单的例子:

>>> A = [] 
    >>> A.append(dict()) 
    >>> A.append(dict()) 
    >>> A[0][5] = 7 
    >>> A 
    [{5: 7}, {}] 
    >>> A[1][4] = 8 
    >>> A[0][3] = 9 
    >>> A[1][8] = 10 
    >>> A 
    [{3: 9, 5: 7}, {8: 10, 4: 8}]