python REPL 中的奇怪设置行为
Weird sets behavior in python REPL
我是 python 的新手,经常使用 REPL 检查一些代码片段。
我试图检查一个集合是否包含一个元组,仅基于元组中的第一个值。知道python中的_
就是pass
的意思,就这样写了:
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = {('a',1),('b',2)}
>>> x
{('b', 2), ('a', 1)}
>>> ('a',_) in x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> ('a',1) in x
True
>>> ('a',_) in x
True
正如您所见,第一个 ('a',_) in x
语句产生了 TypeError
,但下一个语句给出了没有错误的输出。
有人可以解释一下这里发生了什么吗?
_
设置为 repl 返回的最后一个非 None
结果。因此 >>> ('a',_) in x
与 >>> ('a', True) in x
相同。另请注意 True
是 1
在 Python.
中的特例
我是 python 的新手,经常使用 REPL 检查一些代码片段。
我试图检查一个集合是否包含一个元组,仅基于元组中的第一个值。知道python中的_
就是pass
的意思,就这样写了:
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = {('a',1),('b',2)}
>>> x
{('b', 2), ('a', 1)}
>>> ('a',_) in x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> ('a',1) in x
True
>>> ('a',_) in x
True
正如您所见,第一个 ('a',_) in x
语句产生了 TypeError
,但下一个语句给出了没有错误的输出。
有人可以解释一下这里发生了什么吗?
_
设置为 repl 返回的最后一个非 None
结果。因此 >>> ('a',_) in x
与 >>> ('a', True) in x
相同。另请注意 True
是 1
在 Python.