counting element occurrences in nested lists

心已入冬 提交于 2019-12-01 04:55:41

问题


This is probably quite a straightforward question, but I can't find an answer elsewhere so I'll ask. What is the best way to find the number of times an element appears in a nested list? For example:

my_list=[[a,b,c,d],[a,b,z,d],[a,c,f,e],[d,w,f,a]]

How would I find how many times 'a' is the first element of the list? Or more generally, how many times 'a' appears in my_list at all? I imagine there's a way to do this with collections.Counter, but I haven't been able to figure it out.

EDIT For my_list, I would like an output of a:3 when counting if it's the first element of the list. If the question was changed to see if b is the second element, the desired output would be b:2


回答1:


Use a nested generator expression:

Counter(x for sublist in my_list for x in sublist)

To count the items in the first position, a different generator expression gets that item for counting:

Counter(sublist[0] for sublist in my_list)

Demo:

>>> from collections import Counter
>>> my_list=[['a','b','c','d'],['a','b','z','d'],['a','c','f','e'],['d','w','f','a']]
>>> Counter(x for sublist in my_list for x in sublist)
Counter({'a': 4, 'd': 3, 'c': 2, 'b': 2, 'f': 2, 'e': 1, 'w': 1, 'z': 1})
>>> Counter(sublist[0] for sublist in my_list)
Counter({'a': 3, 'd': 1})



回答2:


from collections import Counter
from itertools import chain

counts = Counter(chain.from_iterable(my_list))

or generate a new list and use count:

new_list = list(chain.from_iterable(my_list))
print new_list.count(whatever)

If you wanted how many times 'a' is the first, then something like:

sum(1 for el in my_list if el[0] is a) # or == a if object identity is not required



回答3:


>>> from collections import defaultdict, Counter
>>> my_list = [['a', 'b', 'c', 'd'], ['a', 'b', 'z', 'd'], ['a', 'c', 'f', 'e'], ['d', 'w', 'f', 'a']]
>>> pos_count = defaultdict(Counter)
>>> for sublist in my_list:
        for i, c in enumerate(sublist):
            pos_count[c][i] += 1


>>> pos_count['a'][0]
3
>>> pos_count['b'][1]
2


来源:https://stackoverflow.com/questions/11829422/counting-element-occurrences-in-nested-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!