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))
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
看到问题的本质,我想知道使用列表中每个单词的候选人的数量可能会有用。我会这样做:
这将打印出:
在这里我们可以看到candidate1是唯一一个使用“a”的单词,candidate3是唯一一个使用“d”的单词。 这可能不是OP想要的确切解决方案,但我认为可能会有所帮助;)
只需遍历dictionary项并检查是否有任何项在给定键的值内,如果是,则附加在一个列表
cand
中,该列表包含条件所适用的候选项。你知道吗然后,如果列表的长度是1,则返回第一个候选者,如果不是,则返回
None
。你知道吗在代码中,如下所示:
调用时,返回候选2:
或者,可以通过以下步骤创建列表:
相关问题 更多 >
编程相关推荐