【问题标题】:Weird sets behavior in python REPL [duplicate]python REPL中的奇怪设置行为[重复]
【发布时间】: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


【解决方案1】:

_ 设置为 repl 返回的最后一个非None 结果。因此&gt;&gt;&gt; ('a',_) in x&gt;&gt;&gt; ('a', True) in x 相同。另请注意,True 是 Python 中 1 的特例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    相关资源
    最近更新 更多