【发布时间】:2021-01-17 14:56:18
【问题描述】:
我有两个列表。每个列表都包含单词。有些词对两个列表都是通用的,有些则不是。我只想输出 20 个最常用的词,但我的代码显示了所有常用词。我想将范围限制为 20。我不允许使用 COUNTER。
def countwords(lst):
dct = {}
for word in lst:
dct[word] = dct.get(word, 0) + 1
return dct
count1 = countwords(finallist1)
count2 = countwords(finallist2)
words1 = set(count1.keys())
words2 = set(count2.keys())
common_words = words1.intersection(words2)
for i,w in enumerate (common_words,1):
print(f"{i}\t{w}\t{count1[w]}\t{count2[w]}\t{count1[w] + count2[w]}")
预期输出:
common f1 f2 sum
1 program 5 10 15
2 python 2 4 6
.
.
until 20
【问题讨论】:
标签: python python-3.x list