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

时间:2019-08-22 13:54:05

标签: python list match

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

理想情况下,我想将其编写为Dictionarycomp。因此,类似:

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

3 个答案:

答案 0 :(得分:1)

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

尽管为什么要做出命令?我认为dict名称毫无意义,您可以列出匹配计数。它们的索引与原始列表的索引相同。

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

结果是:

[1, 2]

要查找匹配度最高的列表的索引,则可以使用类似以下内容的

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

结果:

[1]

答案 1 :(得分:0)

如果您希望使用以列表名称作为关键字的字典,则可能需要稍微更改输入格式。否则,您必须采取一些技巧性的方法来获取变量的名称。

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']

答案 2 :(得分:0)

如果您不想将列表重新格式化为字典,则可以使用以下函数将列表创建为字典:

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}