【问题标题】:IF statement (checking for a string in a list) behave weirdly [duplicate]IF 语句(检查列表中的字符串)行为怪异[重复]
【发布时间】:2013-10-21 18:10:39
【问题描述】:

这可能是一个愚蠢的问题,但是为什么这段代码会这样呢?

>>> test = ['aaa','bbb','ccc']
>>> if 'ddd' or 'eee' in test:
...     print True
... 
True
>>> 

我不希望在 stdio 上打印任何内容,因为 IF 语句中的字符串都不在列表中。

我错过了什么吗?

【问题讨论】:

    标签: python list


    【解决方案1】:

    你的测试应该是

    if 'ddd' in test or 'eee' in test:
    

    在您当前拥有的代码中,“ddd”字符串被评估为布尔值,并且由于它不是空的,因此它的布尔值为 True

    【讨论】:

      【解决方案2】:

      if 'ddd' or 'eee' in test

      被评估为:

      if ('ddd') or ('eee' in test):

      因为一个非空字符串总是True,所以or操作短路并返回True

      >>> bool('ddd')
      True
      

      要解决这个问题,您可以使用:

      if 'ddd' in test or 'eee' in test:

      any:

      if any(x in test for x in ('ddd', 'eee')):

      【讨论】:

        【解决方案3】:

        你在这里遗漏了一些东西:

        if 'ddd' or 'eee' in test:

        相当于:

        if ('ddd') or ('eee' in test):

        因此这将永远是 True,因为 'ddd' 被认为是 True。


        你想要:

        if any(i in test for i in ('ddd', 'eee')):
        

        【讨论】:

          【解决方案4】:
          >>> if 'ddd'
          ...     print True
          

          将打印

          True
          

          所以你应该写:

          >>> if 'ddd' in test or 'eee' in test:
          ...     print True
          

          为了得到你想要的结果。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-09-09
            • 2015-12-02
            • 2017-06-01
            • 1970-01-01
            • 2017-10-25
            • 2015-02-11
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多