2013-02-12 94 views
1

我通过扫描文档进行阅读中每一行的列表。根据列表元素和列表字典键的值

我保存这一个叫

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一样空白。我知道字典与此有关,但我不知道如何避免这种情况发生。

回答

3

列表是可变的;对同一列表的多个引用将会看到您对其所做的所有更改。 testList[:] = []表示:将该列表中的每个索引替换为具有空列表的。因为您在不同的地方(包括字典值中)引用了相同的列表,所以您会看到无处不在的变化。

相反,刚点testList空列表,而不是:

testList = [] 

您使用的空分片分配语法应该只使用,如果你想清除内容列表的,不当你只是想创建一个新的空列表。

>>> foo = [] 
>>> bar = foo 
>>> foo.append(1) 
>>> bar 
[1] 
>>> foo is bar 
True 
>>> foo[:] = [] 
>>> bar 
[] 
>>> foo = ['new', 'list'] 
>>> bar 
[] 
>>> foo is bar 
False 
+0

感谢您的帮助。我只是需要正确使用这些更新等。 – TWhite 2013-02-14 16:32:42

0

你必须做一个deepcopy的,see copy.html

dict_offices[patent_offices[office_index]] = copy.deepcopy(testList) 

例如:

l = [1,2,3] 
b = l 
del l[:] 
print(b) 
---> [] 

l = [1,2,3] 
b = copy.deepcopy(l) 
l = [] 
print (b) 
    ---> [1,2,3] 
+0

不要忘记: 进口副本 – 2013-02-12 21:32:02

+0

感谢您的帮助! – TWhite 2013-02-14 16:33:09

相关问题