NAGA
NAGA

Reputation: 338

count occurrence of a list in a list of lists

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

Upvotes: 9

Views: 16113

Answers (4)

Xavier
Xavier

Reputation: 41

You can also use pandas for cleaner code:

pd.Series(A).explode().value_counts()

Upvotes: 4

Ajax1234
Ajax1234

Reputation: 71451

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

Upvotes: 10

Mohd
Mohd

Reputation: 5613

Depending on your output, you can loop through a set of your list and print each item with its count() from the original list:

for x in set(map(tuple, A)):
    print '{} = {}'.format(x, A.count(list(x)))

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78556

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

Upvotes: 6

Related Questions