python - "in"和 "not in"语句在 python 中如何工作

标签 python

我主要学习 C 语言,并花了很多时间了解它的底层实现。但我最近开始学习 python。所以这里有很多不同于 C 的怪癖。

“in”语句在 python 中如何工作?

if x in array:
   #the usage of an in statement produces a boolean
for x in array:
   #the usage of an in statement produces an iterable

也作为附带问题。 'Not' 可以放在 bool 表达式前面,类似于 '!'在 C 中,或者它可以放在 python 中的“in”语句前面。这怎么可能?

if not x == 5:
   #makes sense because 'x == 5' evaluates to a boolean
if x not in array:
   #the statement 'in array' is not a boolean
   #shouldn't it be 'if not x in array'

这两种情况怎么可能?他们的评估方式不应该保持一致吗?现在,我认为这是因为 Python 是一种解释型语言,解释器可以根据周围的语法做不同的事情。

解释或解释链接会非常有帮助,我一直找不到任何解决这个问题的方法。

最佳答案

您混淆了两个完全不相关的语法。

一个是声明,参见 for statement文档。 in是固定语法的一部分:

for_stmt ::=  “for” target_list “in” expression_list “:” suite
              [“else” “:” suite]

你使用 for 的那一刻开始一行,in部分是必需的,就像 :是必须的。并且不要混淆 Python 的 for用 C for环形; Python 的是 For Each construct .因此它不会“产生”一个可迭代对象,它需要一个可迭代对象作为输入。

另一个是membership test operation ,运算符是一种表达式:

The operators in and not in test for membership.

它旨在应用于容器(而不仅仅是可迭代对象)。

两者都严重依赖 Python 的 OO 特性,这是 C 无法做到的。如果您想在其他语言中找到等效项,请查看 C++、Java 或 C# 中的概念,而不是 C。

for <expr> in <iterable>需要 iterable object ,可以产生元素的东西,一个接一个。 C++ 有一个 equivalent concept , 在 Java 中有相似之处 iteratorsstreams .

<expr> [not] in <expr>只要求右边的表达式结果支持成员测试,但如果没有显式的钩子(Hook)可用于成员测试,Python 将回退到迭代。 notnot in简单地反转 in 的结果手术。

C++ 和 Java 对此没有标准的抽象,不同的容器类型各自实现自己的拼写(在 C++ 中大多数称之为 find ,例如 set::find map::find ,而 Java 通常选择 contains 变体,给出你 Set.contains() Map.containsKey() )。

关于python - "in"和 "not in"语句在 python 中如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45707721/

相关文章:

在 Heroku 上安装 Buildpack 后出现 Python ImportError

python - Python 中的类型 - Google Appengine

python - 将矩形添加到使用 Cartopy python 制作的 map 中以选择子空间

python - 使用pyserial发送二进制数据

python - 使用 cv2.VideoCapture() 从 IP 摄像机读取流

python - jupyter-console 无法启动,但 jupyter-notebook 很好

python - 执行程序时出现错误 "NameError: name ' TLSExtSupportedGroup' is not defined"

python - 如何在 python 中使用 selenium webdriver 滚动网页?

python - Pandas Lookup 将被弃用——优雅高效的替代方案

python - 在数据库中具有类似实例的行为