【问题标题】:unhashable type 'list' error不可散列的类型“列表”错误
【发布时间】:2016-10-28 01:55:12
【问题描述】:

我正在使用下面的代码来统计一个特定数字在numpy数组中出现的次数,对字典进行降序排序然后返回

km_0 = [indian,chinese,italian,mexican,indian,indian,chinese,italian] #numpy array
#The ord_dict should be like this {indian:3, chinese:2, italian:2, mexican:1} 

def labels(cluster):
    label_count ={}
    for i in cluster[0]:
        if i in label_count:
            label_count[i] += 1
        else:
            label_count[i] =1
    ord_dict = OrderedDict(sorted(label_count.items(), key=lambda kv:kv[1], reverse=True))

    return ord_dict

函数调用

lc = labels(km_0)

但是,它会抛出以下错误

<ipython-input-8-72f0a128bdd4> in labels(cluster)
      9     label_count ={}
     10     for i in cluster[0]:
---> 11             if i in label_count:
     12                 label_count[i] += 1
     13             else:

TypeError: unhashable type: 'list'

【问题讨论】:

  • 打印j的值,它的类型是list
  • 首先j 是未定义的,你的意思是i,其次你想看看j 是字典label_count 还是value 的键,我是猜测键。
  • 你需要告诉我们km_0是什么。
  • 你想要for j in cluster[0]:而不是i吗?
  • 模拟你的问题的运行示例应该很容易。就目前而言,您希望我们找到您未显示的代码中的错误。那成功率不高!

标签: python python-3.x pandas


【解决方案1】:

也许您可以从collection Counter 雇用而不是建立自己的柜台:

from collections import Counter, OrderedDict
x = "hello world"
print(OrderedDict(sorted(Counter(x).items(), key=lambda t: t[1], reverse=True))) 
#prints OrderedDict([('l', 3), ('o', 2), (' ', 1), ('e', 1), ('d', 1), ('h', 1), ('r', 1), ('w', 1)])

我还是不知道你的j 是什么我猜这是i 的错字

编辑:

以上适用于普通数组,但对于 numpy,请使用以下使用 numpy 的 unique() 函数调用:

#replace array_name with like your `i`
unique, counts = numpy.unique(array_name, return_counts=True)

#Then zip them together to make a dictionary

counted = dict(zip(unique, counts))

#then toss it into OrderedDict

print(OrderedDict(sorted(counted.items(), key=lambda t: t[1], reverse=True))) 

有关 numpy.unique 的更多信息see here.

【讨论】:

  • 不适用于 ndarray,因为它们也是不可散列的。
  • 哦 OP 更新了他的问题,猜猜我会更新我的答案
【解决方案2】:

既然错字已经解决了,那我就另辟蹊径了。如果您专门寻找numpy.array,那么您可以使用MooingRawr 的解决方案Counter。但是,为了提高性能,您可以使用原生 Numpy 计数器,例如 count_nonzero

import numpy as np

def cnt(arr):
    counts = {i: np.count_nonzero(arr == i) for i in range(arr.min(), arr.max() + 1)}
    return OrderedDict(sorted(counts.items(), key=lambda x: x[1], reverse=True))

x = np.random.random_integers(50, size=100)
y = np.random.random_integers(50, size=(10, 10))

【讨论】:

    猜你喜欢
    • 2017-03-11
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 2017-12-27
    • 2021-01-28
    • 2015-07-05
    • 2017-07-11
    相关资源
    最近更新 更多