Python:字典的返回键

2024-04-25 18:12:16 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
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想要的确切解决方案,但我认为可能会有所帮助;)

只需遍历dictionary项并检查是否有任何项在给定键的值内,如果是,则附加在一个列表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

相关问题 更多 >