0
A
回答
2
你可以只喂Counter
生成器表达式:
cnt = Counter(word for sublist in multiple for word in sublist)
cnt
Out[40]: Counter({'apple': 3, 'ball': 2, 'cat': 2})
sum(cnt.values())
Out[41]: 7
名单是巨大的,所以我使用的只是一个虚拟实例
multiple=[['apple','ball','cat']['apple','ball']['apple','cat'].......]
words=['apple','ball','cat','duck'......]
word = 'apple'
cnt = Counter()
total = 0
for i in multiple:
for j in i:
if word in j:
cnt[word] +=1
total += cnt[word]
我想这样的输出中的对象列表
我并没有真正看到您的words
列表。你没有使用它。
如果您需要过滤掉不在words
的话,让words
一个set
,不一个list
。
words = {'apple','ball','cat','duck'}
cnt = Counter(word for sublist in multiple for word in sublist if word in words)
否则你会得到O(n ** 2)的行为应该是O(n)操作。
0
这工作在Python 2.7和Python 3.x的:
from collections import Counter
multiple=[['apple','ball','cat'],['apple','ball'],['apple','cat']]
words=['apple','ball','cat','duck']
cnt = Counter()
total = 0
for i in multiple:
for word in i:
if word in words:
cnt[word] +=1
total += 1
print cnt #: Counter({'apple': 3, 'ball': 2, 'cat': 2})
print dict(cnt) #: {'apple': 3, 'ball': 2, 'cat': 2}
print total #: 7
print sum(cnt.values()) #: 7
在Python 2.x中,你应该使用的.itervalues()
代替.values()
即使两者的工作。
短一点的解决方案,基于roippi的回答是:
from collections import Counter
multiple=[['apple','ball','cat'],['apple','ball'],['apple','cat']]
cnt = Counter(word for sublist in multiple for word in sublist)
print cnt #: Counter({'apple': 3, 'ball': 2, 'cat': 2})
相关问题
- 1. 总计两列,对应两列表中的一个agregate
- 2. 计数和总计列表
- 3. 链接列表中的对象计数
- 4. 如何从唯一列表和计数器对象创建计数列表?
- 5. 如何获取另一个列表中的列表的总和?
- 6. 总计在数据表中的列中
- 7. 计数ListView中的列表项总数
- 8. 列表中值的总和计划
- 9. 总和对象的属性列表
- 10. R(dplyr):相对于列表中第一个值的值的总和列表
- 11. 找到一个列表的列表中重复的对象
- 12. 数据绑定到xaml中的对象列表中的对象列表中的对象列表
- 13. 将对象列表复制到另一个对象中另一个对象的另一个列表中
- 14. 循环列表如果一个列表或一个新的列表中有对象,如果一个对象
- 15. C#序列化一个对象与其中的对象列表
- 16. 总和另一个工作表中的列的总和
- 17. MySQL的 - 在一个表中一列的总和与其他表
- 18. 计划,让每一个第5和第7的每个对象的唯一列表(列表)从一个数组
- 19. 返回一个列表中的n个整数的总和
- 20. node.js中列表中的总和数字
- 21. java返回数组列表的一个对象的数组列表另一个对象的其余对象
- 22. 使用列表对象列表和搜索对象列表中的项目(python)
- 23. Python中列表的总和
- 24. 列表中的负整数的总和
- 25. 计算列表中所有对象的总成本字典
- 26. ios Restkit - 用另一个列表中的列表映射对象
- 27. 访问列表中的第一个对象列表
- 28. 转换列表的STR对象到一个列表对象
- 29. 列表中的每个数据帧的列总和,给出一个唯一的数据框与总和
- 30. 总和/ Python中对象列表的一个属性的平均值
,做你会得到什么输出? –
我无法获得所有计数器对象的正确总数。它给出了不同的总数 – user3470490