是否有一种pythonic方法可以优先使用集合来计算列表列表中的元素?
lol = [[1,2,3],[4,2],[5,1,6]]
输出:
1: 2
2: 2
3: 1
4: 1
5: 1
6: 1
答案 0 :(得分:3)
from collections import Counter
import itertools
a= [[1,2,3],[4,2],[5,1,6]]
print Counter(itertools.chain(*a))
#output Counter({1: 2, 2: 2, 3: 1, 4: 1, 5: 1, 6: 1})
b=Counter(itertools.chain(*a))
for key,val in b.iteritems():
print key,':',val
输出:
1 : 2
2 : 2
3 : 1
4 : 1
5 : 1
6 : 1
与itertools相比,执行此操作但效率较低的其他方式(感谢200OK)
a= [[1,2,3],[4,2],[5,1,6]]
sum(map(Counter, a), Counter())
#output {1: 2, 2: 2, 3: 1, 4: 1, 5: 1, 6: 1}
答案 1 :(得分:0)
from collections import Counter
import itertools
lol = [[1,2,3],[4,2],[5,1,6]]
Counter(itertools.chain.from_iterable(lol))
输出
Counter({1: 2, 2: 2, 3: 1, 4: 1, 5: 1, 6: 1})