Python 中 any() 和 all() 的用法
Python 内置函数 any() 和 all() 的作用是什么?请给出实用示例。
回答
我是大山
any(iterable):只要有一个元素为 True,返回 True;空迭代器返回 Falseall(iterable):所有元素都为 True,返回 True;空迭代器返回 True
# 检查列表中是否有偶数
nums = [1, 3, 5, 7]
any(x % 2 == 0 for x in nums) # False
# 检查字符串是否全部为字母
s = 'Hello'
all(c.isalpha() for c in s) # True
# 检查字典中所有值都满足条件
scores = {'math': 85, 'english': 92, 'science': 78}
all(v >= 60 for v in scores.values()) # True
# 与 map 结合
nums = [2, 4, 6, 8]
all(map(lambda x: x % 2 == 0, nums)) # True
这两个函数短路求值,找到结果后立即停止迭代。