Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Perhaps what you are looking for is something like:

print {i: X.count(i) for i in X}

from itertools import groupby

X = [[1,2], [5,1], [1,2], [2,-1] , [5,1]]

for key, group in groupby(sorted(X)):
    print key, len(list(group))

[1, 2] 2
[2, -1] 1
[5, 1] 2

If X is large some optimization may be added.

If elements in X can be replaced to be tuples instead of lists than dictionary comprehension approach may be used as well:

X = [(1,2), (5,1), (1,2), (2,-1) , (5,1)]
print {i: X.count(i) for i in X}

or even:

X = [(1,2), (5,1), (1,2), (2,-1) , (5,1)]
print {i: X.count(i) for i in set(X)}

(let the Python professionals correct me)