【问题标题】:Python: Returning key of dictionaryPython:返回字典的键
【发布时间】:2016-11-25 20:42:50
【问题描述】:

如果我有一个单词列表:

list_of_words = ['great','debate','stronger']

还有一本字典:

dictionary = {'candidate1':['corruption','election'],'candidate2': ['lady','draintheswamp','stronger','debate'],'candidate3':['healthcare','oil']}

我必须创建一个函数来检测单词列表的生成者。

在上面的例子中:'Candidate2' 最有可能是 list_of_words 的产生者

请不要导入任何模块。效率不是这里的主要关注点。

【问题讨论】:

  • 为什么不能导入任何模块?

标签: python list python-3.x loops dictionary


【解决方案1】:

只需遍历字典项并检查是否有任何项在给定键的值内,如果是,则附加到包含条件成立的候选者的列表 cand 中。

然后,如果列表的长度为 1,则返回第一个候选者,如果不是,则返回 None。

在代码中,如下所示:

def find_candidate():
    cand = []
    for i,j in dictionary.items():
        if any(v in j for v in list_of_words):
            cand.append(i)
    return cand[0] if len(cand) == 1 else None

当被调用时,它返回候选 2:

find_candidate()
'candidate2'

或者,列表创建可以通过理解来完成:

def find_candidate():
    c = [k for k, j in dictionary.items() if any(v in j for v in list_of_words)]
    return c[0] if len(c) == 1 else None

【讨论】:

  • OP 的问题:给定 list_of_words=['a','b','c'] 和 dictionary={'candidate1':['a','b'],'候选人2':['a']}它应该返回'candidate1'吗?如果是这样,这个解决方案就行不通了。
【解决方案2】:

看到问题的性质,我认为了解使用列表中每个单词的候选人数量可能很有用。这就是我的处理方式:

def get_candidate(list_of_words, candidates):
    stats={}
    for word in list_of_words:
        stats[word] = []
        for candidate, candidate_words in candidates.items():
            if word in candidate_words:
                stats[word].append(candidate)

    return stats

list_of_words=['a','b','c','d']
candidates={'candidate1':['a','b','c'], 'candidate2':['b','c'], 'candidate3':['c','d']}

print(get_candidate(list_of_words, candidates))

这会打印出来:

{
 'a': ['candidate1'], 
 'c': ['candidate3', 'candidate2', 'candidate1'], 
 'b': ['candidate2', 'candidate1'], 
 'd': ['candidate3']
}

这里我们可以看到,candidate1 是唯一使用单词 'a' 的,而 Candidate3 是唯一使用单词 'd' 的。 这可能不是 OP 正在寻找的确切解决方案,但我认为它可能会有所帮助;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 2022-01-13
    • 2018-11-01
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 2019-06-26
    相关资源
    最近更新 更多