[英]Formal interpretation of `in` in Python's `for` loops
I know that the in
operator can be used in Python as a short-hand of the following (generally speaking, not considering any hidden equality issues or anything): 我知道
in
运算符可以在Python中用作以下代码的缩写(通常来说,不考虑任何隐藏的相等性问题或其他事项):
for item in list1:
if item == thingToCheck:
return True
return False
However, I was wondering about the technical meaning of in
in the actual for item in list1
line- obviously there is another meaning to in
, since Python wouldn't generate every single possible value of item
and see if item in list1
. 不过,我想知道的技术含义
in
实际for item in list1
线-明明还有另外一个意义in
,因为Python不会产生的每一个可能的值item
,看看item in list1
。 On a related note, are Python for
loops ever made without in
? 与此相关的是,是否有Python
for
循环曾经没有in
?
in
calls the __contains__
method (of list
in this case) in
调用__contains__
方法(在这种情况下为list
)
For list
and tuple
this is linear search 对于
list
和tuple
这是线性搜索
For dict
and set
it uses a hash 对于
dict
并set
它使用哈希
When used in a for loop, in
just means take the next item from the iterable until it runs out. 当在for循环使用,
in
仅仅意味着从迭代采取的下一个项目,直到用完。
You can imagine it's something like this 你可以想象是这样的
it = iter(list1)
while True:
try:
item = next(it)
except StopIteration:
break
if item == thingToCheck:
return True
return False
No, you won't find a for
loop without in
, because it is syntactically necessary, see Python language reference . 不,如果没有
in
,您将找不到for
循环,因为从语法上讲这是必需的,请参阅Python语言参考 。 As Greg pointed out, the fact, that the same keyword is used, does not mean, that the internal processing is similar let alone identical. 正如Greg所指出的,使用相同的关键字这一事实并不意味着内部处理相似,更不用说相同了。 Similar is the never-dying discussion concerning programming languages, where
=
has the two roles of assignment and as comparison operator. 关于编程语言的永无止境的讨论与此类似,其中
=
具有分配和作为比较运算符的两个角色。 Programming languages are designed for readability and to abstract from what is actually happening, and the abstraction increases with the level of the language. 编程语言旨在提高可读性并从实际发生的事情中抽象出来,并且抽象程度随语言级别的提高而增加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.