Given an item, how can I count its occurrences in a list in Python?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
To count the number of diverse elements having a common type:
gives
3
, not 6I've compared all suggested solutions (and a few new ones) with perfplot (a small project of mine).
Counting one item
For large enough arrays, it turns out that
is slightly faster than the other solutions.
Counting all items
As established before,
is what you want.
Code to reproduce the plots:
2.
Counting the occurrences of one item in a list
For counting the occurrences of just one list item you can use
count()
Counting the occurrences of all items in a list is also known as "tallying" a list, or creating a tally counter.
Counting all items with count()
To count the occurrences of items in
l
one can simply use a list comprehension and thecount()
method(or similarly with a dictionary
dict((x,l.count(x)) for x in set(l))
)Example:
Counting all items with Counter()
Alternatively, there's the faster
Counter
class from thecollections
libraryExample:
How much faster is Counter?
I checked how much faster
Counter
is for tallying lists. I tried both methods out with a few values ofn
and it appears thatCounter
is faster by a constant factor of approximately 2.Here is the script I used:
And the output:
Why not using Pandas?
Output:
If you are looking for a count of a particular element, say a, try:
Output:
if you want a number of occurrences for the particular element:
If you can use
pandas
, thenvalue_counts
is there for rescue.It automatically sorts the result based on frequency as well.
If you want the result to be in a list of list, do as below