Python中的所有

Any和All是python中提供的两个内置函数,用于连续和/或。

null

任何 如果任何项为true,则返回true。如果为空或全部为False,则返回False。任何操作都可以被认为是对所提供的iterables的一系列操作。 它会使执行短路,即在知道结果后立即停止执行。

语法: 任何(可编辑列表)

# Since all are false, false is returned
print ( any ([ False , False , False , False ]))
# Here the method will short-circuit at the
# second item (True) and will return True.
print ( any ([ False , True , False , False ]))
# Here the method will short-circuit at the
# first (True) and will return True.
print ( any ([ True , False , False , False ]))


输出:

False
True
True

全部的 如果所有项都为true(或者如果iterable为空),则返回true。所有这些都可以被认为是对所提供的可重用项的一系列操作。它还会使执行短路,即在知道结果后立即停止执行。

语法: 全部(可编辑列表)

# Here all the iterables are True so all
# will return True and the same will be printed
print ( all ([ True , True , True , True ]))
# Here the method will short-circuit at the
# first item (False) and will return False.
print ( all ([ False , True , True , False ]))
# This statement will return False, as no
# True is found in the iterables
print ( all ([ False , False , False ]))


输出:

True
False
False

实例

# This code explains how can we
# use 'any' function on list
list1 = []
list2 = []
# Index ranges from 1 to 10 to multiply
for i in range ( 1 , 11 ):
list1.append( 4 * i)
# Index to access the list2 is from 0 to 9
for i in range ( 0 , 10 ):
list2.append(list1[i] % 5 = = 0 )
print ( 'See whether at least one number is divisible by 5 in list 1=>' )
print ( any (list2))


输出:

See whether at least one number is divisible by 5 in list 1=>
True

# Illustration of 'all' function in python 3
# Take two lists
list1 = []
list2 = []
# All numbers in list1 are in form: 4*i-3
for i in range ( 1 , 21 ):
list1.append( 4 * i - 3 )
# list2 stores info of odd numbers in list1
for i in range ( 0 , 20 ):
list2.append(list1[i] % 2 = = 1 )
print ( 'See whether all numbers in list1 are odd =>' )
print ( all (list2))


输出:

See whether all numbers in list1 are odd =>
True

真值表:- 图片[1]-Python中的所有-yiteyi-C++库

本文由 马扬克·拉瓦特 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享