我是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)]}
可以使用
collections.counter
获取每个列表中的单词数,然后operator.itemgetter
仅获取应用于单词列表的单词。那么这个结果的最大值就是你的数字。你知道吗其结果如下:
但为什么要做口述呢?口述的名字毫无意义,我想,你可以列一个匹配计数的清单。它们的索引与原始列表相同。你知道吗
这将导致:
要找到匹配项最多的列表的索引,可以使用以下方法:
结果:
如果您想要一个以列表名称作为键的字典,您可能需要稍微更改输入的格式。否则,您必须采取一些黑客的方法来获得一个变量的名称。你知道吗
如果你只想得到最匹配的列表,你可以采取不同的方法。你知道吗
如果您不想将列表重新格式化为字典,以下是一个将列表创建为字典的函数:
输出:
相关问题 更多 >
编程相关推荐