python - 为什么我不能将 <some list>.append 添加到 python 集?

标签 python set

为什么我可以将普通的可调用对象和方法添加到集合中,但不能 <some list>.append (例如)?

例如:

>>> l = []
>>> s = set()
>>> s.add(l.append)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> type(l.append)
<type 'builtin_function_or_method'>
>>> type(map)
<type 'builtin_function_or_method'>
>>> s.add(map)
>>> def func(): print 'func'
... 
>>> s.add(func)
>>> print s
set([<built-in function map>, <function func at 0x10a659758>])

编辑:我注意到 l.append.__hash__()也给出这个错误

最佳答案

您不能将 list 添加到集合中,因为列表是可变的。只能将不可变对象(immutable对象)添加到集合中。

l.append 是一个实例方法。您可以将其视为元组 (l, list.append) — 也就是说,它是绑定(bind)到特定列表 l 的 list.append() 方法. list.append() 方法是不可变的,但 l 不是。因此,虽然您可以将 list.append 添加到集合中,但您不能添加 l.append

这个有效:

>>> s.add(list.append)

这不起作用:

>>> s.add((l, list.append))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

关于python - 为什么我不能将 <some list>.append 添加到 python 集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13596430/

相关文章:

python - 当我使用 np.power() 时,如何在 numba 中设置 `parallel=True`?

python - scipy.optimize.leastsq : not a proper array of floats

C++ STL 集合用法

java - 容量适配 Java 集合

python - 使用 SleekXMPP 连接到 Facebook 聊天

python - urllib3 如何查找 Http 错误的代码和消息

php - 相当于 PHP 中的 std::set?

c++ - std::lower_bound 与 std::set 的时间复杂度是多少?

java - 我们可以重写Guava的intersection方法来比较对象吗?

python - 索引超出范围 - Python 中的快速排序