表达式中的 Python 'in' 关键字与 for 循环中的关键字 [英] Python 'in' keyword in expression vs. in for loop
问题描述
我理解 in
操作符在这段代码中的作用:
I understand what the in
operator does in this code:
some_list = [1, 2, 3, 4, 5]
print(2 in some_list)
我也明白 i
将采用此代码中列表的每个值:
I also do understand that i
will take on each value of the list in this code:
for i in [1, 2, 3, 4, 5]:
print(i)
我很好奇 for
循环中使用的 in
运算符是否与第一个代码中使用的 in
运算符相同.
I am curious if the in
operator used in the for
loop is the same as the in
operator used in the first code.
推荐答案
它们是相同的概念但不相同的操作符.
They are the same concept but not the same operators.
在 print(2 in some_list)
示例中,in
是处理几种不同情况的运算符.in
运算符的 Python 文档 给出细节,我解释如下: x in y
调用 y.__contains__(x)
如果 y
有一个 >__contains__
成员函数.否则,x in y
尝试遍历 y.__iter__()
以找到 x
,或调用 y.__getitem__(x)
如果 __iter__
不存在.复杂性在于为旧代码和新代码提供一致的成员资格测试—__contains__
如果您要实现自己的类,就是您想要的.
In the print(2 in some_list)
example, in
is an operator that handles several different situations. The Python docs for the in
operator give the details, which I paraphrase as follows: x in y
calls y.__contains__(x)
if y
has a __contains__
member function. Otherwise, x in y
tries iterating through y.__iter__()
to find x
, or calls y.__getitem__(x)
if __iter__
doesn't exist. The complexity is to provide consistent membership testing for older code as well as newer code — __contains__
is what you want if you're implementing your own classes.
在 for
循环中,in
只是一个标记,它将循环索引变量与您正在循环的任何内容分开.for
循环的 Python 文档 讨论语义,我将其解释如下:in
之后的任何内容都在循环开始时求值以提供迭代器.然后为迭代器的每个元素运行循环体(除非 break
或其他控制流更改).for
语句不关心 __contains__
或 __getitem__
.
In the for
loop, in
is just a marker that separates the loop-index variable from whatever you're looping over. The Python docs for the for
loop discuss the semantics, which I paraphrase as follows: whatever comes after in
is evaluated at the beginning of a loop to provide an iterator. The loop body then runs for each element of the iterator (barring break
or other control-flow changes). The for
statement doesn't worry about __contains__
or __getitem__
.
编辑 @Kelvin 提出了一个很好的观点:您可以根据自己的新样式类(class foo(object)
):
Edit @Kelvin makes a good point: you can change the behaviour of in
with respect to your own new-style classes (class foo(object)
):
- 要更改
x in y
,定义y.__contains__()
. - 要更改
for x in y
,定义 <代码>y.__iter__().
这篇关于表达式中的 Python 'in' 关键字与 for 循环中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!