我正在尝试编写一个 Python 函数 one_mode(l)
,它接受一个非空列表 l
并返回一对及其模式和频率模式。 (如果有多种模式,可以返回任意一种。)
到目前为止我已经...
from scipy import stats
def one_mode(l):
return stats.mode(l)
适用于以下测试:
one_mode([5, 6, 7, 5]) == (5,2)
但不是为了测试:
one_mode([5, 6, 7, 5, 6]) in {(5, 2), (6, 2)}
在这种情况下它给了我
unhashable type: 'numpy.ndarray'
使用我当前的代码有什么办法解决这个问题吗?
最佳答案
如果您将 stats.mode
的结果强制为一个元组,您的查找将起作用:
代码:
from scipy import stats
def one_mode(l):
mode = stats.mode(l)
# return first mode results as tuple
return mode[0][0], mode[1][0]
测试代码:
assert one_mode([5, 6, 7, 5]) == (5, 2)
assert one_mode([5, 6, 7, 5, 6]) in {(5, 2), (6, 2)}
关于python - 查找模式时出现无法散列的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42547073/