在 Python 中检查列表中的所有元素是否为真

在 Python 中检查列表中的所有元素是否为 True

Check if all elements in a list are True in Python

使用该all()函数检查列表中的所有元素是否都是True,例如
if all(item is True for item in my_list):如果列表中的所有值都等于,则all()函数将返回

否则返回。
TrueTrueFalse

主程序
my_list = [True, True, True] if all(item is True for item in my_list): # 👇️ this runs print('All list elements are True') else: print('Not all list elements are True') # 👇️ True print(all(item is True for item in my_list))

我们使用生成器表达式来遍历列表。

生成器表达式用于对每个元素执行某些操作或选择满足条件的元素子集。

在每次迭代中,我们检查当前值是否等于True并返回结果。

all()内置函数接受一个可迭代对象作为参数,如果可迭代对象中True所有元素都为真(或可迭代对象为空)则返回。

主程序
my_list = [True, True, True] # 👇️ True print(all(item is True for item in my_list))

如果all()函数发现一个不等于 的值True,它将短路返回False

请注意,如果传入的可迭代对象为空,则该all()函数会返回True任何条件。
主程序
my_list = [] if all(item is True for item in my_list): # 👇️ this runs print('All list elements are True') else: print('Not all list elements are True') # 👇️ True print(all(item is True for item in my_list))

如果您考虑一个并非所有值都是 的空列表True,请检查列表的长度。

主程序
my_list = [] if len(my_list) > 0 and all(item is True for item in my_list): print('All list elements are True') else: # 👇️ this runs print('Not all list elements are True')
我们使用了and布尔运算符,因此要使if 块运行,必须满足两个条件。

list长度不大于0,因此else块运行。

或者,您可以使用该list.count()方法。

检查列表中的所有值是否为真:

  1. 使用list.count()方法计算True列表中的值。
  2. 如果True值的数量等于列表的长度,则列表中的所有值都是True.
主程序
my_list = [True, True, True] if my_list.count(True) == len(my_list): # 👇️ this runs print('All list elements are True') else: print('Not all list elements are True')

list.count()方法接受一个值并返回所提供的值在列表中出现的次数。

主程序
my_list = [True, True, True] print(my_list.count(True)) # 👉️ 3

如果列表中True值的数量与列表的长度相同,则列表仅包含True值。