python - 如果所有元素都符合不使用 "if all"的要求

标签 python list for-loop

我正在通过一本书学习 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/

相关文章:

Matlab从数组设置参数

python - 如何在 Pandas 数据帧上应用具有模式的 bool 过滤器?

python:如何重建需要编译的依赖项

c# - 为什么 List<T>.Add 和 List<T>.Remove 将元素复制到新数组中而不是实际添加和删除?

python - 在python中获取列表的旋转

string - BATch forfiles,带引号的命令

javascript - 动态点击事件问题

python - 告诉Webassets不要缩小一些代码

python - 如何在当前页面的 Pelican 站点顶部生成所有语言的链接(文章)

c# - 带有列表的 Entity Framework 查询