Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python Counter for a list of lists?

Tags:

python

list

count

I'd like to count the frequency of items in a list by calling a collections.Counter. The trick is that my list itself contains lists:

Given:

[[1,"a"], [2,"b"], [3,"c"], [1,"a"], [1,"a"]

Produce:

{
  ([1,"a"], 3),
  ([2,"b"], 1),
  ([3,"c"], 1)
}

When I instantiate Counter using my list, I get TypeError: unhashable type: 'list'.

Can Counter do what I want? Is there some other (reasonably efficient) method for doing this?

like image 848
Abe Avatar asked Oct 21 '17 03:10

Abe


2 Answers

Counter returns a hash table. For this to work the keys (what is getting counted) have to be hashable. Unfortunately lists are not hashable, which is why you are seeing your error.

One work-around would be to cast each internal list to a tuple.

from collections import Counter

x = [[1,"a"], [2,"b"], [3,"c"], [1,"a"], [1,"a"]]
Counter(tuple(item) for item in x)
# returns:
Counter({(1, 'a'): 3, (2, 'b'): 1, (3, 'c'): 1})
like image 171
James Avatar answered Sep 28 '22 03:09

James


Typically only immutable types are hashable. You can convert your list to tuples using map.

from collections import Counter
x = [[1,"a"], [2,"b"], [3,"c"], [1,"a"], [1,"a"]
print(Counter(map(tuple, x)))
like image 29
GWW Avatar answered Sep 28 '22 01:09

GWW