Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

python - counting element occurrences in nested lists

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...