python - 基于列表元素和列表值的字典键

标签 python list dictionary python-2.7

我正在扫描一份文档,列出读入的每一行。

我将其保存到名为

的列表中
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/

相关文章:

Python 在迭代过程中就地修改字典条目

python - Swiging 作为模板函数的类成员函数

python - 如何从 Python 中的列表中分离值?

python - 如何生成带有蜂鸣声的 WAV 文件?

java - 在java中,删除和添加元素或评估(如果必须的话)哪个更快?

javascript - 将 ListView 的值传递给ajax

dictionary - 从 clojure 映射中的动态键获取值

python - 如何取消字典初始化? python3.3

python - Matplotlib y 轴值未正确显示

python - Pyodbc 找不到 FreeTDS 驱动