我正在通过一本书学习 Python:练习是编写一个程序,如果列表中的所有数字都是奇数,则打印 True。
我用这个方法明白了
if all(x % 2 == 1 for x in list):
但“if all”方法尚未得到解释。他们只在示例中使用 while、if、for 和 bool 值。此外,这似乎是一种反身练习,它可以做到,也许不能。可以使用上面的基本工具来完成吗?
最佳答案
如果您查看文档:https://docs.python.org/3/library/functions.html#all
all(iterable) .
Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:
def all(iterable):
for element in iterable:
if not element:
return False
return True
所以 if all(x % 2 == 1 for x in li):
大致转换为
def are_all_odds(num_list):
#Flag to keep track if we encounter an even number
flag = True
for num in num_list:
#Once we encounter a even number, we break the for loop
if num % 2 != 1:
flag = False
break
#Return the flag
return flag
我们可以通过做来测试这个功能
print(are_all_odds([1, 2, 3, 4]))
#False
print(are_all_odds([1, 3, 5]))
#True
也只是一个建议,list
是 python 内置关键字,所以不要在变量中使用它:)
关于python - 如果所有元素都符合不使用 "if all"的要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56070323/