Python如何使用Any和All?代码示例和解析

Any和All是python中提供的两个内置插件, 用于连续的And/Or。

Any

如果任何一项为True, 则返回true。如果为空或全部为假, 则返回False。可以将任何内容视为对提供的可迭代对象进行的一系列OR操作。

它将执行短路, 即一旦知道结果就立即停止执行。

语法:any(迭代列表)

# 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

All

如果所有项目均为True(或iterable为空), 则返回true。可以将所有内容视为对提供的可迭代对象的一系列AND操作。这也使执行短路, 即一旦知道结果就立即停止执行。

语法:all(迭代列表)

# 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

真值表:-

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

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

更多Python开发技术相关内容请参考:lsbin - IT开发技术https://www.lsbin.com/

查看以下更多Python相关的内容:

猜你喜欢

转载自blog.csdn.net/u014240783/article/details/115387002