python-3.x - 在多个列表中查找经常出现的单词

标签 python-3.x

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

我使用了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 个列表中。

最佳答案

没有计数器:

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

关于python-3.x - 在多个列表中查找经常出现的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57463644/

相关文章:

Python:Windows 上的编码问题(Bokeh 绘图库)

python - 跨模块共享单例

python - 绘制时翻转纹理pyopengl

python - 过滤对象在迭代后变为空?

python - 如何比较 Python 中的两个列表并计算所有匹配项?

python - 将字符串解析为 int,下划线失败

python - 如何在一行中计算数据框中的并发事件?

python-3.x - python文件不读取bazel中的文件夹

python - 如何在 __init__ 中设置只读 @property

python-3.x - 如何在 TKINTER 中为条目总和定位 def