我正在扫描一份文档,列出读入的每一行。
我将其保存到名为
的列表中testList = []
当我完成填充此列表后,我想将其设置为字典中的值,该字典的键基于另一个列表的元素。 这个想法是它应该看起来像这样:
testList = ['InformationA', 'InformationB', 'Lastinfo']
patent_offices = ['European Office', 'Japan Office']
dict_offices[patent_offices[0]] = testList
或
dict_offices = {'European Office' : ['InformationA', 'InformationB', 'Lastinfo'],
'Japan Office' : ['Other list infoA', 'more infoB']}
我想稍后输入 dict_offices['European Office']
并打印列表。
但是因为我是在阅读文档时动态收集的,所以我删除并重用了 testList
。我所看到的是,它被清除后,它也在词典的链接中被清除。
如何创建字典并保存它,以便我可以在每次循环中重用 testList?
这是我的代码:
patent_offices = []
dict_offices = {}
office_index = 0
testList = []
# --- other conditional code not shown
if (not patent_match and start_recording):
if ( not re.search(r'[=]+', bString)): #Ignore ====== string
printString = fontsString.encode('ascii', 'ignore')
testList.append(printString)
elif (not start_recording and patent_match):
dict_offices[patent_offices[office_index]] = testList
start_recording = True
office_index += 1
testList[:] = []
这本词典已正确更新,并且看起来与我想要的一模一样,直到我调用
testList[:] = []
线。字典会变成空白,就像 testList
一样。我知道字典与此相关,但我不知道如何避免这种情况发生。
最佳答案
列表是可变的;对同一列表的多次引用将看到您对其所做的所有更改。 testList[:] = []
表示:用空列表替换此列表中的每个索引。因为您在不同的位置引用相同的列表(包括在字典值中),所以您会看到随处反射(reflect)的更改。
相反,只需将 testList
指向一个新空列表即可:
testList = []
仅当您想要清除列表的内容时,才应使用您使用的空切片赋值语法,而不是当您只想创建新的空列表时。
>>> foo = []
>>> bar = foo
>>> foo.append(1)
>>> bar
[1]
>>> foo is bar
True
>>> foo[:] = []
>>> bar
[]
>>> foo = ['new', 'list']
>>> bar
[]
>>> foo is bar
False
关于python - 基于列表元素和列表值的字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14841956/