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
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)]}
解决方案
您可以使用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]
推荐阅读
- angular - 角度表单生成器验证
- javascript - Css - 如何在内联样式中包含不同浏览器的不同属性?
- reactjs - 在 React 数据库调用不起作用时按日期排序 - 只是先返回最旧的
- c# - 如何在 Localhost 中将客户端计算机上的网站作为安全 Web 访问
- android - obj.apply{ func1() } 的结果与 obj.func1() 不同
- python - 如何使我的 python 代码可分发?
- c# - 蓝牙设备被检测为低功耗且具有相同 MAC 地址和名称的普通蓝牙设备
- oracle - ORA-06502:PL/SQL:数字或值错误:字符到数字的转换错误 - TO_DATE 错误?
- javascript - svg 元素在浏览器中的位置
- amazon-web-services - 在未显示站点地图和博客的 aws 静态网站上部署 nuxt