开放的编程资料库

当前位置:我爱分享网 > Python教程 > 正文

Python 任何和所有内置函数

Pythonany&all函数教程展示了如何在Python中使用any和all内置函数。

任何Python

any内置函数返回True如果iterable的任何元素为真。如果可迭代对象为空,则返回False

def any(it):
  for el in it:
      if el:
          return True
  return False

any等价于上面的代码。

vals = [False, False, True, False, False]

if any(vals):
    print('There is a truthy value in the list')
else:
    print('There is no truthy value in the list')

使用any函数,我们检查列表中是否有真值。

Python任意实例

我们的下一个目标是找出是否有一些用户比指定年龄大。

#!/usr/bin/python

from datetime import datetime, date
from dateutil.relativedelta import relativedelta


users = [
  {'name': 'John Doe', 'date_of_birth': '1987-11-08', 'active': True},
  {'name': 'Jane Doe', 'date_of_birth': '1996-02-03', 'active': True},
  {'name': 'Robert Brown', 'date_of_birth': '1977-12-12', 'active': True},
  {'name': 'Lucia Smith', 'date_of_birth': '2002-11-17', 'active': False},
  {'name': 'Patrick Dempsey', 'date_of_birth': '1994-01-04', 'active': True}
]

user_dts = [datetime.strptime(user['date_of_birth'], "%Y-%m-%d") for user in users]

val = 40
today = datetime.now()
data = [relativedelta(today, dt).years > val for dt in user_dts]

if any(data):
    print(f'There are users older than {val}')
else:
    print(f'There are no users older than {val}')

我们有一个用户列表。每个用户都表示为字典。字典的关键字之一是出生日期。

user_dts = [datetime.strptime(user['date_of_birth'], "%Y-%m-%d") for user in users]

通过Python列表理解,我们创建了一个用户日期时间对象列表。使用strptime函数,我们将date_of_birth字符串值转换为datetime对象。

val = 40

我们想知道是否有超过40岁的用户。

today = datetime.now()

我们获取当前日期和时间。

data = [relativedelta(today, dt).years > val for dt in user_dts]

通过另一个列表理解,我们创建了一个布尔值列表。relativedelta函数计算当前日期时间和用户生日日期时间之间的年份。如果年差大于给定值(40),则表达式返回True;否则为假。

if any(data):
    print(f'There are users older than {val}')
else:
    print(f'There are no users older than {val}')

我们将创建的布尔值列表传递给any函数。

$ ./users_age.py
There are users older than 40

至少有一位四十岁以上的用户。

Python全部

all内置函数返回True如果可迭代对象的所有元素都为真(或者如果可迭代对象为空)。

def all(it):
    for el in it:
        if not el:
            return False
    return True

all等价于上面的代码。

vals = [True, False, True, True, True]

if all(vals):
    print('All values are truthy')
else:
    print('All values are not thruthy')

使用all函数,我们检查所有值是否为真。

Python全实战例子

我们想知道是否所有用户都处于活动状态。

#!/usr/bin/python

users = [
  {'name': 'John Doe', 'occupation': 'gardener', 'active': True},
  {'name': 'Jane Doe', 'occupation': 'teacher', 'active': True},
  {'name': 'Robert Brown', 'occupation': 'driver', 'active': True},
  {'name': 'Lucia Smith', 'occupation': 'hair dresser', 'active': False},
  {'name': 'Patrick Dempsey', 'occupation': 'programmer', 'active': True}
]


if all([user['active'] for user in users]):
    print('All users are active')
else:
    print('There are inactive users')

我们有一个用户列表。用户具有active属性。

if all([user['active'] for user in users]):
    print('All users are active')
else:
    print('There are inactive users')

我们使用all函数检查所有用户是否都处于活动状态。

$ ./users_active.py
There are inactive users

在本教程中,我们使用了anyall内置函数。

列出所有Python教程。

未经允许不得转载:我爱分享网 » Python 任何和所有内置函数

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏