python中的any()

any()源码:

def any(*args, **kwargs): # real signature unknown
    """
    Return True if bool(x) is True for any x in the iterable.
    
    If the iterable is empty, return False.
    """
    pass

any() 函数将一个可迭代对象作为参数,只要该可迭代对象中至少有一项为 True,就返回 True。如果列表中所有元素都为False,则返回False;否则有一个为Ture,就返回True

语法结构:

any(iterable)
  • 对于迭代中的任何 x,如果 bool(x) 是 True,返回 True
  • 如果迭代是空,返回 False

示例代码:

复制代码
list_1 = [0, 0, 0, 1, 0, 0, 0, 0]
# any(a list with at least one non-zero entry) returns True
print(any(list_1))
# Output True
 
list_2 = [0j, 0, 0, 0.0, 0, 0, 0.0, 0]
# any(a list of zeros) returns False
print(any(list_2))
# Output False
 
list_3 = [True, False, False]
# any(a list with at least one True value) returns True
print(any(list_3))
# Output True
 
list_4 = ["", "", "code more"]
# any(a list with at least one non-empty string) returns True
print(any(list_4))
# Output True
 
list_5 = ["", "", ""]
# any(a list of empty strings) returns False
print(any(list_5))
# Output False
复制代码

运行结果:

使用any() 函数检查字符串中的数字

s = "dsag123"
lst = [a.isdigit() for a in s]
print(any(lst)

运行结果:

使用any()函数将多个条件与逻辑 OR 组合在一起

示例代码:

复制代码
a, b, c, d = False, False, True, False
 
if a or b or c or d:
    print(True)
else:
    print(False)
 
# 将a, b, c, d放到一个可迭代对象中,如列表list
lst = [a, b, c, d]
# 使用any()
if any(lst):
    print(True)
else:
    print(False)
复制代码

运行结果:

 

 

转载自:https://blog.csdn.net/weixin_44799217/article/details/127378570

 

posted on   一先生94  阅读(361)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示