Python any()

any() 函数在可迭代对象中**只要有一个元素为 True**,就返回 True。否则,返回 False

示例

boolean_list = ['True', 'False', 'True']

# check if any element is true result = any(boolean_list)
print(result) # Output: True

any() 语法

any() 的语法是

any(iterable)

any() 参数

any() 函数在 Python 中接受一个可迭代对象(列表字符串字典等)。


any() 返回值

any() 函数返回一个布尔值

  • 如果可迭代对象中至少有一个元素为真,则返回 True
  • 如果所有元素都为假或可迭代对象为空,则返回 False
条件 返回值
所有值为真 True
所有值为假 False
一个值为真(其他为假) True
一个值为假(其他为真) True
空可迭代对象 False

示例 1:在 Python 列表上使用 any()

# True since 1,3 and 4 (at least one) is true
l = [1, 3, 4, 0]
print(any(l))
# False since both are False l = [0, False]
print(any(l))
# True since 5 is true l = [0, False, 5]
print(any(l))
# False since iterable is empty l = []
print(any(l))

输出

True
False
True
False

any() 方法对于元组集合的工作方式与列表类似。


示例 2:在 Python 字符串上使用 any()

# At east one (in fact all) elements are True
s = "This is good"
print(any(s))
# 0 is False # '0' is True since its a string character s = '000' print(any(s)) # False since empty iterable s = ''
print(any(s))

输出

True
True
False

示例 3:将 any() 与 Python 字典一起使用

对于字典,如果所有键(不是值)都为假,或者字典为空,any() 返回 False。如果至少有一个键为真,any() 返回 True

# 0 is False
d = {0: 'False'}
print(any(d))

# 1 is True
d = {0: 'False', 1: 'True'}
print(any(d))
# 0 and False are false d = {0: 'False', False: 0} print(any(d)) # iterable is empty d = {}
print(any(d))
# 0 is False # '0' is True d = {'0': 'False'} print(any(d))

输出

False
True
False
False
True
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战