python计数器列表列表?

Abe*_*Abe 2 python list count

我想通过调用collections.Counter来计算列表中项目的频率。诀窍是我的列表本身包含列表:

鉴于:

[[1,"a"], [2,"b"], [3,"c"], [1,"a"], [1,"a"]
Run Code Online (Sandbox Code Playgroud)

生产:

{
  ([1,"a"], 3),
  ([2,"b"], 1),
  ([3,"c"], 1)
}
Run Code Online (Sandbox Code Playgroud)

当我使用列表实例化Counter时,我得到 TypeError: unhashable type: 'list'.

柜台可以做我想要的吗?还有其他方法(合理有效)吗?

Jam*_*mes 5

Counter返回哈希表。为此,键(要计数的键)必须是可哈希的。不幸的是,列表不可散列,这就是为什么看到错误的原因。

一种解决方法是将每个内部列表转换为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})
Run Code Online (Sandbox Code Playgroud)