2024-10-02 10:23:12 发布
网友
我是python新手
我有一张旗帜的清单。这个列表的长度是可变的。我想检查列表中的所有变量是否都是真的
我试过了
if (all in flags[x]==True): finalFlags[x-1]=True
但当只有一个标志为真时,最终的标志变为真
所有和任何函数都可用于检查列表中的布尔值
test_list = []
all(iterable) returns True if all elements of the iterable are considered as true values (like reduce(operator.and_, iterable)).
any(iterable) returns True if at least one element of the iterable is a true value (again, using functional stuff, reduce(operator.or_, iterable)).
当您需要检查所有值是否为真时,您可以使用all()函数,如下所示
all(test_list) #will return true
此外,您可以使用any()检查所有为true的值,但此时,您需要将列表元素从true转换为false,并检查是否存在任何true,我们可以说原始列表中存在false,并且在出现任何()返回false,这意味着没有真值,因此在原始列表中没有真值
not all(not element for element in data)
由于您没有发布示例,我可以这样假设:
my_flags = [True, False, True, True, True, False] valid_flags = 0 for flag in my_flags: if flag == True: valid_flags += 1 if len(my_flags) == valid_flags: print("Total match") else: print("Matched ", valid_flags, " out of ", len(my_flags))
finalFlags = False if all(flags): finalFlags=True
编辑:根据Chris的评论简化:
finalFlags = all(flags)
所有和任何函数都可用于检查列表中的布尔值
当您需要检查所有值是否为真时,您可以使用all()函数,如下所示
此外,您可以使用any()检查所有为true的值,但此时,您需要将列表元素从true转换为false,并检查是否存在任何true,我们可以说原始列表中存在false,并且在出现任何()返回false,这意味着没有真值,因此在原始列表中没有真值
由于您没有发布示例,我可以这样假设:
编辑:根据Chris的评论简化:
相关问题 更多 >
编程相关推荐