迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中检查列表中的所有值是否为零

作者:迹忆客 最近更新:2022/11/29 浏览次数:

使用 all() 函数检查列表中的所有值是否为零,例如 if all(item == 0 for item in my_list):。 如果列表中的所有值都为零,则 all() 函数将返回 True,否则返回 False

my_list = [0, 0, 0]

if all(item == 0 for item in my_list):
    # 👇️ this runs
    print('All elements in the list are 0')
else:
    print('Not all elements in the list are 0')

# 👇️ True
print(all(item == 0 for item in my_list))

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

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

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

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

my_list = [0, 0, 0]

# 👇️ True
print(all(item == 0 for item in my_list))

如果 all() 函数找到一个非零值,它将短路返回 False。

请注意 ,如果传入的可迭代对象为空,则 all() 函数会针对任何条件返回 True。

my_list = []

if all(item == 0 for item in my_list):
    # 👇️ this runs
    print('All elements in the list are 0')
else:
    print('Not all elements in the list are 0')

# 👇️ True
print(all(item == 0 for item in my_list))

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

my_list = []

if len(my_list) > 0 and all(item == 0 for item in my_list):
    print('all elements in the list are 0')
else:
    # 👇️ this runs
    print('Not all elements in the list are 0')

我们使用了 and 布尔运算符,因此要运行 if 块,必须满足两个条件。

该列表的长度不大于 0,因此运行 else 块。

或者,我们可以使用 list.count() 方法。

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

使用 list.count() 方法计算列表中的 0 个值。

如果 0 值的数量等于列表的长度,则列表中的所有值都是 0。

my_list = [0, 0, 0]

if my_list.count(0) == len(my_list):
    # 👇️ this runs
    print('All values in the list are equal to 0')

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

my_list = [0, 0, 0]

print(my_list.count(0))  # 👉️ 3

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

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便