bernie2436
bernie2436

Reputation: 23911

Is there any python module that will count frequency of (list, list) tuples?

I have a list of tuples, which are each a pair of lists. So my data looks like:

mylist = [(['foo', 'bar'], ['bar', 'bar']),(['bar', 'bar'],['bar', 'bar']),(['foo', 'bar'], ['bar', 'bar'])]

I want to do something like:

pprint.pprint(Counter(mylist).mostCommon(1)) # returns {(['foo', 'bar'], ['bar', bar']) : count 2}

However when I do Counter(mylist) python is throwing an error, "unhashable type list" -- like in this question. python: unhashable type error

I know I could roll my own counter like here but it would certainly be much slower than Python's. Is there any python module that will do this this for me?

Upvotes: 1

Views: 612

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1123400

Simply convert your lists to tuples if you want to count them by exact contents:

Counter((tuple(l1), tuple(l2)) for l1, l2 in mylist).most_common(1)

Demo:

>>> from collections import Counter
>>> mylist = [(['foo', 'bar'], ['bar', 'bar']), (['bar', 'bar'], ['bar', 'bar']), (['foo', 'bar'], ['bar', 'bar'])]
>>> Counter((tuple(l1), tuple(l2)) for l1, l2 in mylist).most_common(1)[0]
((('foo', 'bar'), ('bar', 'bar')), 2)

Now your contents are hashable and can be counted. You can always turn the keys back into lists if you have to.

Upvotes: 6

Sukrit Kalra
Sukrit Kalra

Reputation: 34513

>>> Counter(tuple(map(tuple, elem)) for elem in mylist).most_common(1)
[((('foo', 'bar'), ('bar', 'bar')), 2)]

Upvotes: 3

Related Questions