Python any()函数

时间:2020-02-23 14:42:25  来源:igfitidea点击:

Python any()函数是内置函数之一。
它以iterable作为参数,如果iterable中的任何元素为True,则返回True。
如果iterable为空,则返回False。

Python any()函数

Python any()函数是一种实用程序方法,是以下函数的快捷方式。

def any(iterable):
  for element in iterable:
      if element:
          return True
  return False

我们来看一些python any()函数的示例。

带有布尔值的Python any()示例

# iterable has at least one True
list_bools = [True, True, True]

print(any(list_bools))

# iterable none of the elements are True
list_bools = [False, False]

print(any(list_bools))

输出:

True
False

带有空迭代的Python any()

# iterable is empty
list_bools = []

print(any(list_bools)) # False

Python any()与字符串列表

# iterable elements are True string (at least one)
list_strs = ['True', 'false']

print(any(list_strs))

# iterable any elements is true string with different case
list_strs = ['fff', 'true']

print(any(list_strs))

# iterable any elements are not true string
list_strs = ['abc', 'def']

print(any(list_strs))

# iterable all elements are empty string
list_strs = ['', '']

print(any(list_strs))

输出:

True
True
True
False

当我们想要一个对象布尔值时,python在对象中寻找__bool__函数。

如果未定义__bool__函数,则如果定义了len()函数。
如果len()输出为非零,则对象布尔值被视为True。

如果一个类都没有定义__len__()或者__bool __()函数,则其所有实例均被视为True。

Python 3使用__bool__函数来检查对象的布尔值,如果您使用的是Python 2.x,则必须实现__nonzero__函数。

带有自定义对象的Python any()

让我们使用自定义类测试上述说明。
我们将创建一个自定义的Employee类,并在列表中使用其对象,然后在其上调用any()函数。

class Employee:
  name = ""

  def __init__(self, n):
      self.name = n

list_objs = [Employee("hyman"), Employee("Lisa")]
print(any(list_objs))

list_objs = [Employee("A"), Employee("D")]
print(any(list_objs))

输出:

True
True

由于我们的Employee类没有定义__len __()__bool __()函数,因此其布尔值是True。

让我们继续为Employee类定义__len __()函数,如下所示。

def __len__(self):
      print('len function called')
      return len(self.name)

现在,早期代码片段的输出将是:

len function called
True
len function called
True

注意,当any()与Employee对象的列表一起使用时,会调用len()函数。
由于iterable中的第一个对象返回True,因此不需要评估其他元素的布尔值。

现在,我们为Employee类定义__bool__函数,看看上面的代码会发生什么。

def __bool__(self):
      print('bool function called')
      if len(self.name) > 3:
          return True
      else:
          return False

输出:

bool function called
True
bool function called
bool function called
False

从输出中可以清楚地看到,如果定义了__bool__函数,那么它将用于获取python对象的布尔值。

请注意,第二个列表的any()函数输出为False,并且为列表中的所有对象检索了布尔值。