表达式中的Python'in'关键字与for循环中的Python [英] Python 'in' keyword in expression vs. in for loop

查看:134
本文介绍了表达式中的Python'in'关键字与for循环中的Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解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)):

这篇关于表达式中的Python'in'关键字与for循环中的Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆