Python 修改列表中包含的词典
我目前正在编写一些从文本文件中读取行的代码。线被分成3个不同的段,第一个段是用户ID 例如,一行将如下所示:Python 修改列表中包含的词典,python,list,dictionary,Python,List,Dictionary,我目前正在编写一些从文本文件中读取行的代码。线被分成3个不同的段,第一个段是用户ID 例如,一行将如下所示: 11 490 5 exampleList[10] = {490:5} 我有一个包含用户数量的元素列表,其中每个元素对应一个用户(例如exampleList[4]存储第五个用户的数据) 每个列表元素都包含一个不定长的字典,其中键是行的第二段,值是行的第三段 如果同一用户的ID出现在另一行中,则字典的长度(键值对的数量)会增加。其思想是,当遇到具有相同用户ID的另一行时,该行中的数据将
11 490 5
exampleList[10] = {490:5}
我有一个包含用户数量的元素列表,其中每个元素对应一个用户(例如exampleList[4]
存储第五个用户的数据)
每个列表元素都包含一个不定长的字典,其中键是行的第二段,值是行的第三段
如果同一用户的ID出现在另一行中,则字典的长度(键值对的数量)会增加。其思想是,当遇到具有相同用户ID的另一行时,该行中的数据将附加到对应于该用户的列表元素中的字典中
例如,上面的行将存储在如下内容中:
11 490 5
exampleList[10] = {490:5}
如果程序读到另一行这样的内容:11239
列表项将自身更新为:
exampleList[10] = {490:5, 23:9}
我的程序的工作方式是首先收集用户数量,然后创建如下列表:
exampleList = [{}] * numberOfUsers
然后,它使用re.finditer
提取行中空白的位置,然后通过基本字符串操作提取数字
这一部分工作得很好,但我不确定如何更新列表中的字典,即向字典添加新的键值对
我读过关于使用for循环的文章,但这对我来说不起作用,因为这会将它添加到单元格中的每个字典中,而不是仅仅将它附加到某个单元格中的字典中
示例代码:
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}]
出于某种原因,它会用所有值填充列表中的所有词典。您可以通过索引访问词典。下面是一个简单的例子:
>>> 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}]
我不确定我是否正确理解了您的问题,但我能够得到您想要的输出。 请注意,此解决方案完全忽略列表中的第四个值
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)
请分享你的一些代码。如果你想要一个字典列表,为什么要创建一个列表?你能输入一些可靠的示例和预期的输出吗?我已经编辑了代码,正在读取的文件示例,以及预期的输出和实际的输出。
cL=[{}]*numOfUsers
是个坏主意:请参阅列表示例,但同样的问题也会影响词典。。我刚刚注意到,exampleList=[[]]*numberOfUsers
,出于同样的原因,这也是个坏主意。太好了!非常感谢–如果我让问题变得难以理解,我很抱歉,我不是最擅长沟通的。我不认为问题在于你的解释,我认为这只是一个复杂的问题,很难用文字表达。但对我来说,理解问题是99%的战斗,编写解决方案并不复杂