📅  最后修改于: 2020-10-30 05:52:50             🧑  作者: Mango
Python all()函数接受一个可迭代的对象(例如list,dictionary等)。如果传递的iterable中的所有项目都为true,则返回True,否则返回False。如果可迭代对象为空,则all()函数返回True。
all (iterable)
让我们看看all()如何用于列表?
# all values true
k = [1, 3, 4, 5]
print(all(k))
# all values false
k = [0, False]
print(all(k))
# one false value
k = [1, 3, 4, 0]
print(all(k))
# one true value
k = [0, False, 5]
print(all(k))
# empty iterable
k = []
print(all(k))
输出:
True
False
False
False
True
下面的示例显示all()如何用于字典。
# Both the keys are true
dict1 = {1: 'True', 2: 'False'}
print(all(dict1))
# One of the key is false
dict2 = {0: 'True', 1: 'True'}
print(all(dict2))
# Both the keys are false
dict3 = {0: 'True', False: 0}
print(all(dict3))
# Empty dictionary
dict4 = {}
print(all(dict4))
# Here the key is actually true because
# 0 is non-null string rather than a zero
dict5 = {'0': 'True'}
print(all(dict5))
输出:
True
False
False
True
True
下面的示例显示all()对元组的工作方式。
# all true values
t1 = (1, 2, 3, 4, 5)
print(all(t1))
# one false value
t2 = (0, 1, "Hello")
print(all(t2))
# all false values
t3 = (0, False , 0)
print(all(t3))
# one true value, all false
t4 = (True, 0, False)
print(all(t4))
输出:
True
False
False
False