Python any & all 内置函数
最后修改于 2024 年 1 月 29 日
在本文中,我们将展示如何在 Python 中使用 any 和 all 内置函数。
Python any
any
内置函数在可迭代对象中任何元素为真时返回 True
。如果可迭代对象为空,则返回 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 any 实用示例
我们的下一个目标是找出是否有任何用户年龄大于指定年龄。
users_age.py
#!/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 列表推导式,我们创建一个用户 datetime 对象列表。使用 strptime
函数,我们将 date_of_birth
字符串值转换为 datetime
对象。
val = 40
我们想知道是否有任何用户超过 40 岁。
today = datetime.now()
我们获取当前的日期和时间。
data = [relativedelta(today, dt).years > val for dt in user_dts]
使用另一个列表推导式,我们创建一个布尔值列表。relativedelta
函数计算当前 datetime 和用户的生日 datetime 之间的年份差。如果年份差大于给定值 (40),则表达式返回 True;否则返回 False。
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
至少有一个用户超过 40 岁。
Python all
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 all 实用示例
我们想知道所有用户是否都处于活动状态。
users_active.py
#!/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
来源
在本文中,我们使用了 any
和 all
内置函数。
作者
列出所有 Python 教程。