如何计算另一个lis中两个列表之间的匹配

2024-09-28 22:30:36 发布

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

我是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

如何将其转换为具有以下结构的词典(list1:1、list2:2等…)

我的输入将是26个列表的列表,rotationsplitlist,和一个单词的参考列表,word\u list。你知道吗

最理想的情况是,我想把它写成一个dictionarycomp。比如说:

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

Tags: the方法in列表forcountblue单词
3条回答

可以使用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]

如果您想要一个以列表名称作为键的字典,您可能需要稍微更改输入的格式。否则,您必须采取一些黑客的方法来获得一个变量的名称。你知道吗

words = ['red', 'blue', 'yellow', 'black']
lists = {
    'list1': ['the', 'black', 'dog'],
    'list2': ['the', 'blue', 'blue', 'dog']
}

result = {list_name: sum([list_items.count(word) for word in words]) for list_name, list_items in lists.items()}

# Result
{
    "list1": 1,
    "list2": 2
}

如果你只想得到最匹配的列表,你可以采取不同的方法。你知道吗

words = ['red', 'blue', 'yellow', 'black']
lists = [
    ['the', 'black', 'dog'], 
    ['the', 'blue', 'blue', 'dog']
]

result = sorted(lists, key=lambda list_items: sum([list_items.count(word) for word in words]), reverse=True)[-1]

# Result
['the', 'blue', 'blue', 'dog']

如果您不想将列表重新格式化为字典,以下是一个将列表创建为字典的函数:

word_match = lambda match_list, list1, list2: {'list'+str(l+1): len(list([x for x in [list1, list2][l] if x in match_list])) for l in range(0, len([list1, list2]))}

words = ['red', 'blue', 'yellow', 'black']
list1 = ['the', 'black', 'dog']
list2 = ['the', 'blue', 'blue', 'dog']

print(word_match(words, list1, list2))

输出:

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

相关问题 更多 >