📌  相关文章
📜  Python|检查列表中的任何元素是否满足条件

📅  最后修改于: 2022-05-13 01:54:27.524000             🧑  作者: Mango

Python|检查列表中的任何元素是否满足条件

有时,在使用Python列表时,我们可能会遇到过滤列表的问题。执行此过滤操作的标准之一可以是检查列表中是否存在满足条件的任何元素。让我们讨论一些可以解决这个问题的方法。

方法#1:使用列表推导
使用循环可以很容易地解决这个问题。但是这种方法提供了一个单一的方法来解决这个问题。列表推导仅检查满足条件的任何元素。

# Python3 code to demonstrate working of
# Check if any element in list satisfies a condition
# Using list comprehension
  
# initializing list
test_list = [4, 5, 8, 9, 10, 17]
  
# printing list
print("The original list : " + str(test_list))
  
# Check if any element in list satisfies a condition
# Using list comprehension
res = True in (ele > 10 for ele in test_list)
  
# Printing result
print("Does any element satisfy specified condition ? : " + str(res))
输出 :
The original list : [4, 5, 8, 9, 10, 17]
Does any element satisfy specified condition ? : True

方法 #2:使用any()
这是解决此特定问题的最通用方法。在这个我们只是使用Python库扩展的内置函数来解决这个任务。它检查任何满足条件的元素并返回 True 以防找到任何一个元素。

# Python3 code to demonstrate working of
# Check if any element in list satisfies a condition
# Using any()
  
# initializing list
test_list = [4, 5, 8, 9, 10, 17]
  
# printing list
print("The original list : " + str(test_list))
  
# Check if any element in list satisfies a condition
# Using any()
res = any(ele > 10 for ele in test_list)
  
# Printing result
print("Does any element satisfy specified condition ? : " + str(res))
输出 :
The original list : [4, 5, 8, 9, 10, 17]
Does any element satisfy specified condition ? : True