python-3.x - 在多个列表中查找常用词
问题描述
我有 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 个中。
解决方案
没有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
推荐阅读
- elasticsearch - 如何在 Elasticsearch 中存储布尔数组并执行 XOR 操作?
- r - R:在数据框中创建一个新列,使用来自另一个数据框的列名、条件和值
- swift - 在 UITableView 中选择单元格后更新视图控制器中的项目
- graph - 如何使用 neoj4 图数据库获取语句?
- html - 使用 Bootstrap 4 对齐列时出现问题
- angular - 有没有办法在模板中隐藏关闭容器?
- python - 如何创建一个字典来反向查找每个都有集合的列表项?
- swift - 在 Swift 4.2 中无法撤消、重做和再次撤消
- javascript - 在顺序循环中修改多个 Highcharts
- swift - 导航控制器不释放内存,内存泄漏?