Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count occurrence of a list in a list of lists

Tags:

python

list

count

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
like image 550
NAGA Avatar asked Jul 10 '17 18:07

NAGA


People also ask

How do you count occurrences in a list?

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.

How do you count how many times a value appears in a 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.

How do you count the number of occurrences of all elements in a list in Python?

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.

How do you count multiple lists in Python?

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.


2 Answers

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))
like image 87
Ajax1234 Avatar answered Oct 11 '22 10:10

Ajax1234


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))
like image 33
Moses Koledoye Avatar answered Oct 11 '22 09:10

Moses Koledoye