首页 > 解决方案 > 在多个列表中查找常用词

问题描述

我有 5 个单词列表。我需要找到出现在 2 个以上列表中的所有单词。任何单词都可以在列表中出现多次。

我使用了 collections.Counter 但它只返回单个列表中所有单词的频率。

a = ['wood', 'tree', 'bark', 'log']

b = ['branch', 'mill', 'boat', 'boat', 'house']

c = ['log', 'tree', 'water', 'boat']

d = ['water', 'log', 'branch', 'water']

e = ['branch', 'rock', 'log']

例如,这些列表的输出应该是 ['log':4, 'branch':3] 因为 'log' 存在于 4 个列表中,而 'branch' 存在于 3 个中。

标签: python-3.x

解决方案


没有Counter

a = ['wood', 'tree', 'bark', 'log']
b = ['branch', 'mill', 'boat', 'boat', 'house']
c = ['log', 'tree', 'water', 'boat']
d = ['water', 'log', 'branch', 'water']
e = ['branch', 'rock', 'log']

all_lists = [a, b, c, d, e]
all_words = set().union(w for l in all_lists for w in l)

out = {}
for word in all_words:
    s = sum(word in l for l in all_lists)
    if s > 2:
        out[word] = s

print(out)

印刷:

{'branch': 3, 'log': 4}

编辑(打印列表名称):

a = ['wood', 'tree', 'bark', 'log']
b = ['branch', 'mill', 'boat', 'boat', 'house']
c = ['log', 'tree', 'water', 'boat']
d = ['water', 'log', 'branch', 'water']
e = ['branch', 'rock', 'log']

all_lists = {'a':a, 'b':b, 'c':c, 'd':d, 'e':e}
all_words = set().union(w for l in all_lists.values() for w in l)

out = {}
for word in all_words:
    s = sum(word in l for l in all_lists.values())
    if s > 2:
        out[word] = s

for k, v in out.items():
    print('Word : {}'.format(k))
    print('Count: {}'.format(v))
    print('Lists: {}'.format(', '.join(kk for kk, vv in all_lists.items() if k in vv )))
    print()

印刷:

Word : log
Count: 4
Lists: a, c, d, e

Word : branch
Count: 3
Lists: b, d, e

推荐阅读