表达式中的Python'in'关键字与for循环中的Python [英] 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文档为详细信息,我将其解释如下:如果y
具有__contains__
成员函数,则x in y
调用y.__contains__(x)
.否则,x in y
尝试遍历y.__iter__()
以找到x
,或者如果__iter__
不存在,则调用y.__getitem__(x)
.复杂性是为较旧的代码和较新的代码提供一致的成员资格测试.如果要实现自己的类,则需要__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
只是一个标记,用于将loop-index变量与您要遍历的所有内容分开. 用于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)
)更改in
的行为:
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循环中的Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!