【问题标题】:Python: issues with nested {dict : {dict : [list] } } structure and regex matchingPython:嵌套 {dict : {dict : [list] } } 结构和正则表达式匹配的问题
【发布时间】: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


【解决方案1】:

我假设您希望您的输出显示每个句子中出现动物名称的索引。

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_list = ["lion", "fox", "tiger", 'elephant']

sentence_dict = {}

for s in sentence_list:
  sentence_dict[s] = {}
  for a in animal_list:
    sentence_dict[s][a] = []

for sentence in sentence_dict:
    for w in animal_list:
        for m in re.finditer(w, sentence):
            sentence_dict[sentence][w].append(m.start(0))


print sentence_dict

以上代码有如下输出:

{'the quick brown fox': {'tiger': [], 'lion': [], 'fox': [16], 'elephant': []}, 'the lion, the witch and the wardrobe': {'tiger': [], 'lion': [4], 'fox': [], 'elephant': []}, 'lion and tiger and elephant, oh my!': {'tiger': [9], 'lion': [0], 'fox': [], 'elephant': [19]}, 'ellie the elephant': {'tiger': [], 'lion': [], 'fox': [], 'elephant': [10]}}

您的代码不起作用的原因是因为您的 animal_dict 中的列表是同一个对象,因此不是为每个句子/动物对保留单独的列表,每个动物在句子之间共享相同的列表。

【讨论】:

  • 非常感谢,正是我想做的!这让我发疯了。
最近更新 更多