【发布时间】:2019-03-11 23:07:38
【问题描述】:
我是python新手,经常使用REPL检查一些代码sn-ps。
我试图检查一个集合是否包含一个元组,仅基于元组中的第一个值。知道_在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,但下一个给出了一个没有错误的输出。
谁能解释一下这里发生了什么?
【问题讨论】:
-
"知道
_在python中表示pass,'并不表示pass。_只是一个普通的变量名,比如@987654330 @ 或x。在 REPL 中,它被分配 last 输出。在 Python 代码中,通常用作一次性变量的名称,例如列出十个 1,[1 for _ in range(10)]
标签: python python-3.x read-eval-print-loop