迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 检查多个值是否在列表中

作者:迹忆客 最近更新:2022/11/29 浏览次数:

使用 all() 函数检查列表中是否有多个值,例如 if all(value in my_list for value in multiple_values):。 如果所有指定值都在列表中,则 all() 函数将返回 True,否则返回 False。

my_list = ['one', 'two', 'three', 'four', 'five']

multiple_values = ['one', 'two', 'three']

if all(value in my_list for value in multiple_values):
    # 👇️ this runs
    print('All of the values are in the list')
else:
    print('Not all of the values are in the list')

# 👇️ True
print(all(value in my_list for value in multiple_values))

Python 检查多个值是否在列表中

我们使用生成器表达式来迭代多个值的集合。

生成器表达式用于对每个元素执行某些操作或选择满足条件的元素子集。

在每次迭代中,我们检查列表中是否存在当前值并返回结果。

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

如果其中一个值不在列表中,则 all() 函数将短路返回 False。

my_list = ['one', 'two', 'three', 'four', 'five']

multiple_values = ['fifty', 'two', 'three']

if all(value in my_list for value in multiple_values):
    print('All of the values are in the list')
else:
    # 👇️ this runs
    print('Not all of the values are in the list')

# 👇️ False
print(all(value in my_list for value in multiple_values))

python all() 函数检查多个值是否在列表中

或者,我们可以使用 set() 类将值集合转换为集合对象,以便能够使用 issubset() 方法。

my_list = ['one', 'two', 'three', 'four', 'five']

multiple_values = ['one', 'two', 'three']


if set(multiple_values).issubset(my_list):
    # 👇️ this runs
    print('All of the values are in the list')
else:
    print('Not all of the values are in the list')

# 👇️ True
print(set(multiple_values).issubset(my_list))

set.issubset 方法测试集合中的每个元素是否都在提供的序列中。

仅当列表中存在所有指定值时,条件才计算为 True。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便