python IN 运算符的语法

syntax of python IN operator

刚开始学习python我很容易上手,但后来我来到了 IN 运算符,我正在使用的网站显示代码设置的方式我无法做到开始工作,我已经搜索了互联网和堆栈,但没有找到任何可靠的东西,他们写的方式让我相信你可以用这个语句检查一个列表中的多个变量。

if name in ["John", "Rick"]:
    print "Your name is either John or Rick."

但我还没有在互联网上的其他任何地方找到等效的,网站上的在线 IDE 没有给我一个语法错误,但它总是 returns false no不管我在列表中有什么:name.

所以我的问题是:上面的代码有效吗python?如果是这样的话,是什么让它成为 return true?

您将 name 定义为您在评论中所说的列表,因此 Python 的作用如下:

>>> name = ["John", "Rick" ,"tim", "george"] 
>>> name in ["John", "Rick"]
False
>>> name in ["John", "Rick", ["John", "Rick" ,"tim", "george"]]
True
>>> 

x in y 只检查 是否 y 中调用了 x 元素。 检查是否有元素在x 中并且也在y.

这就是为什么以下代码有效而以上代码无效的原因:

>>> name = 'John'
>>> if name in ["John", "Rick"]:
...     print("Your name is either John or Rick.")
...     
... 
Your name is either John or Rick.
>>> 

在这种情况下你需要:

>>> if any(i in ["John", "Rick"] for i in name):
...     print("Your name is either John or Rick.")
...     
... 
Your name is either John or Rick.
>>>