检查条件是否保留在布尔列表中

时间:2015-02-10 03:12:01

标签: python string list boolean

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

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

不确定如何修复它。

3 个答案:

答案 0 :(得分:4)

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

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

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

即可
if any(list):

您还应该避免使用户定义的名称与其中一个内置命令相同。这样做会使内置内容蒙上阴影,并使其在当前范围内无法使用。

答案 1 :(得分:1)

  

任何(迭代):

     

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

您的代码应使用:

 if any(list):

答案 2 :(得分:1)

请注意,如果编写为:

,则代码会更短
if any(file.endswith(suffix, 21, 22) 
       for suffix in ['05', '11', '17', '21', '23']):
相关问题