【问题标题】:syntax of python IN operatorpython IN 运算符的语法
【发布时间】:2015-12-08 01:46:10
【问题描述】:

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

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

但是我还没有在互联网上的其他任何地方找到等效的,该站点上的在线 IDE 并没有给我一个语法错误,但无论我在列表中有什么,它总是返回 false:名称。

所以我的问题是:上面的代码是有效的 python 吗?如果是这样,什么会使它返回 true

【问题讨论】:

  • 好吧,你的代码对我有用。
  • 你能贴出你用来测试它的代码吗?
  • if 语句之前插入print repr(name),再次运行程序,并告诉我们它打印的内容。
  • 首先定义name,比如name = "John"name = 'Rick',然后运行你的代码,它会打印出Your name is either John or Rick.
  • 如果我使用这段代码,它总是打印 else name = ["John", "Rick" ,"tim", "george"] if name in ["John", "Rick"]: print "你的名字不是约翰就是瑞克。" else: print "else" @zwol 与您的编辑它打印 ['John', 'Rick', 'tim', 'george'] else

标签: python syntax logic


【解决方案1】:

您将name 定义为您在 cmets 中所说的列表,所以 Python 是这样做的:

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

x in y 仅检查如果有一个元素称为 xy检查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.
>>> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-11
    • 2011-01-14
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    相关资源
    最近更新 更多