【发布时间】:2016-02-11 22:58:53
【问题描述】:
我一直在试图找出我在使用嵌套字典/列表时遇到的问题。
import re
sentence_list = ["the quick brown fox", "ellie the elephant", "the lion, the witch and the wardrobe", "lion and tiger and elephant, oh my!"]
animal_dict = {"lion":[], "fox":[], "tiger":[], 'elephant':[]}
sentence_dict = {}
for s in sentence_list:
sentence_dict[s] = animal_dict
for sentence in sentence_dict:
for w in sentence_dict[sentence]:
for m in re.finditer(w,sentence):
sentence_dict[sentence][w].append(m.start(0))
print sentence_dict
它给了我以下输出,即它将值附加到字典中每个句子的每个列表中,而不仅仅是当前的:
{'the quick brown fox': {'tiger': [9], 'lion': [4, 0], 'fox': [16], 'elephant': [19, 10]}, \
'the lion, the witch and the wardrobe': {'tiger': [9], 'lion': [4, 0], 'fox': [16], 'elephant': [19, 10]}, \
'lion and tiger and elephant, oh my!': {'tiger': [9], 'lion': [4, 0], 'fox': [16], 'elephant': [19, 10]}, \
'ellie the elephant': {'tiger': [9], 'lion': [4, 0], 'fox': [16], 'elephant': [19, 10]}}
关于如何解决此问题的任何建议?提前致谢!
【问题讨论】:
-
你想做什么?
-
据我所知,代码正在执行您指示它执行的操作。您需要回答上述@zondo 的问题。
-
抱歉,我说得不够清楚 - @Joshua Snider 下面的回答正是我所追求的。
标签: python regex list dictionary