首页 > 解决方案 > 如何计算另一个列表中两个列表之间的匹配

问题描述

我是 Python 新手,正在尝试编写一个程序来告诉我列表列表中的哪些列表包含与另一个列表匹配的最多单词。我希望输出是一个字典,其中包含与列表编号(来自列表列表)相对应的数字键和键列表与比较列表之间匹配数的值。

我尝试过使用几种不同的计数方法,但只能成功地得到一种来显示匹配数。那个方法是:

words = ['red', 'blue', 'yellow', 'black']

list1 = ['the', 'black', 'dog']

list2 = ['the', 'blue', 'blue', 'dog']

results1 = 0

results2 = 0

for w in words:

        results1 += list1.count(w)

        results2 += list2.count(w)

结果1

1

结果2

2

我怎样才能把它变成具有结构的字典(list1:1,list2:2等......)

我的输入将是一个包含 26 个列表的列表,rotationssplitlist 和一个单词的参考列表,word_list。

最理想的是,我想把它写成字典。所以,像:

matchdict = {[i for i in range(len(rotationssplitlist)-1)]: [word_list.count(rotationssplitlist[i] for i in range(len(rotationssplitlist)-1)]}

标签: pythonlistmatch

解决方案


您可以使用collections.counter获取每个列表中的单词数,然后operator.itemgetter仅获取适用于单词列表的单词。然后该结果的最大值将是您的数字。

from collections import Counter
from operator import itemgetter

word_list = ['red', 'blue', 'yellow', 'black']
rotationssplitlist = [
    ['the', 'black', 'dog'],
    ['the', 'blue', 'blue', 'dog']
]
get_words = itemgetter(*word_list)
matchdict = {f'list{i}': max(get_words(Counter(l))) 
             for i, l in enumerate(rotationssplitlist, 1)}

这导致字典如下:

{'list1': 1, 'list2': 2}

虽然为什么要编一个字典?我认为字典名称毫无意义,您可以列出匹配计数。它们将具有与原始列表相同的索引。

matches = [max(get_words(Counter(l))) for l in rotationssplitlist]

这导致:

[1, 2]

要找到匹配最多的列表的索引,您可以使用以下内容:

[i for i, m in enumerate(matches) if m == max(matches)]

结果:

[1]

推荐阅读