Python
I have a list of lists. like
A = [[x,y],[a,b],[c,f],[e,f],[a,b],[x,y]]
I want to count how many times each list occurred in the main list.
My output should be like
[x,y] = 2
[a,b] = 2
[c,f] = 1
[e,f] = 1
Using the count() Function The "standard" way (no external libraries) to get the count of word occurrences in a list is by using the list object's count() function. The count() method is a built-in function that takes an element as its only argument and returns the number of times that element appears in the list.
Use the COUNTIF function to count how many times a particular value appears in a range of cells. For more information, see COUNTIF function.
The easiest way to count the number of occurrences in a Python list of a given item is to use the Python . count() method. The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.
If you want to count multiple items in a list, you can call count() in a loop. This approach, however, requires a separate pass over the list for every count() call; which can be catastrophic for performance. Use couter() method from class collections , instead.
Just use Counter
from collections
:
from collections import Counter
A = [[x,y],[a,b],[c,f],[e,f],[a,b],[x,y]]
new_A = map(tuple, A) #must convert to tuple because list is an unhashable type
final_count = Counter(new_A)
#final output:
for i in set(A):
print i, "=", final_count(tuple(i))
You can use collections.Counter
- a dict subclass - to take the counts. First, convert the sublists to tuples to make them usable (i.e. hashable) as dictionary keys, then count:
from collections import Counter
count = Counter(map(tuple, A))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With