【问题标题】:Searching for items in a list [duplicate]在列表中搜索项目[重复]
【发布时间】:2014-04-21 20:57:19
【问题描述】:

我想说的是,如果它不是这些运算符之一,那么它应该运行if 语句。

if item is ("(" , "+" , "*" , "/" , ")" , "–") == False:

是我目前拥有的,但它不起作用。我应该如何编写它才能使其工作?

【问题讨论】:

  • 永远不要使用is 运算符来比较元组或字符串。

标签: python list


【解决方案1】:

你想要这个:

if item not in ("(" , "+" , "*" , "/" , ")" , "–"):

还有:

  • 您以完全错误的方式使用is 运算符。如果你想检查两件事是否“相等”,就像“相同的字符串/值/...”一样,永远不要使用它。仅用它来测试两件事是否真的相同。作为初学者,您真正需要此功能的唯一情况是测试某事物是否为None(例如foo is Nonefoo is not None
  • foo == Truefoo == False 是你真的不想在 Python 中使用的东西。只需改用foonot foo
  • 请阅读(并关注!Python style guide (PEP8)

【讨论】:

    【解决方案2】:

    您想在此处使用not in 运算符:

    if item not in ("(", "+", "*", "/", ")", "–"):
    

    is 运算符用于测试对象的身份。下面是一个演示:

    >>> class Foo:
    ...     pass
    ...
    >>> f1 = Foo()  # An instance of class Foo
    >>> f2 = Foo()  # A different instance of class Foo
    >>> f3 = f1     # f3 refers to the same instance of class Foo as f1
    >>> f1 is f3
    True
    >>> f1 is f2
    False
    >>>
    

    【讨论】:

      【解决方案3】:

      虽然到目前为止发布的答案是正确的,但它们可以更简单。

      if item not in "(+*/.)-": ...
      

      与列表版本一样有效。这与以下原理相同:

      >>> x = "Hello, world"
      >>> "Hello" in x
      True
      >>> "H" in x
      True
      >>> y = "+"
      >>> y in "(+*/.)-"
      True
      

      这样做的原因是字符串是可迭代的,就像列表一样,所以in 操作符可以正常工作。

      【讨论】:

        【解决方案4】:

        试试:

        if item not in ["(" , "+" , "*" , "/" , ")" , "–"]:
            ...
            ...
            ...
        else:
            ...
        

        您也可以使用字符串使其更短:

        if item not in "(+*/)–":
            ...
            ...
            ...
        else:
            ...
        

        但前提是您的项目是单个字符。

        【讨论】:

          【解决方案5】:

          试试if item not in ["(" , "+" , "*" , "/" , ")" , "–"]:

          【讨论】:

            猜你喜欢
            • 2020-04-05
            • 1970-01-01
            • 1970-01-01
            • 2015-08-28
            • 1970-01-01
            • 2015-08-31
            • 1970-01-01
            • 2023-02-01
            • 2016-08-31
            相关资源
            最近更新 更多