【问题标题】:Checking if conditions hold in boolean list检查条件是否在布尔列表中成立
【发布时间】:2015-04-09 23:58:31
【问题描述】:

如果布尔值列表为真,我正在尝试运行一些函数。 我的列表由布尔函数组成。

list = [file.endswith('05',21,22), file.endswith('11',21,22),
       file.endswith('17',21,22), file.endswith('21',21,22),
       file.endswith('23',21,22)]

if any(True in list) == True:           
    # do something

目前,if 子句给我一个错误

  if any(True in list) == True:
TypeError: 'bool' object is not iterable

不确定如何解决。

【问题讨论】:

  • 不要隐藏内置的list

标签: python string list boolean


【解决方案1】:

any 期待一个可迭代的参数,然后它将运行该参数以查看其是否有任何项目评估为 True。此外,表达式True in list 返回一个不可迭代的布尔值:

>>> lst = [False, True, False]
>>> True in lst
True
>>>

要解决此问题,您只需将列表传递给any

if any(list):

您还应避免将用户定义的名称与内置插件之一相同。这样做会使内置函数黯然失色,并使其在当前范围内无法使用。

【讨论】:

    【解决方案2】:

    任何(可迭代):

    如果可迭代的任何元素为真,则返回真。如果迭代是 为空,返回 False。

    您的代码应该使用:

     if any(list):
    

    【讨论】:

      【解决方案3】:

      请注意,如果写成这样,您的代码会更短:

      if any(file.endswith(suffix, 21, 22) 
             for suffix in ['05', '11', '17', '21', '23']):
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-06
        • 2014-05-02
        • 1970-01-01
        • 1970-01-01
        • 2012-06-18
        • 1970-01-01
        • 2016-08-22
        • 2012-11-23
        相关资源
        最近更新 更多