Python|检查列表中的所有元素是否都符合条件
有时,在使用Python列表时,我们可能会遇到需要检查列表中的所有元素是否符合特定条件的问题。这可以应用在 Web 开发领域的过滤中。让我们讨论可以执行此任务的某些方式。
方法 #1:使用all()
我们可以使用all()
来执行这个特定的任务。在此,我们提供条件,所有元素的验证由all()
内部检查。
# Python3 code to demonstrate working of
# Check if all elements in list follow a condition
# Using all()
# initializing list
test_list = [4, 5, 8, 9, 10]
# printing list
print("The original list : " + str(test_list))
# Check if all elements in list follow a condition
# Using all()
res = all(ele > 3 for ele in test_list)
# Printing result
print("Are all elements greater than 3 ? : " + str(res))
输出 :
The original list : [4, 5, 8, 9, 10]
Are all elements greater than 3 ? : True
方法 #2:使用itertools.takewhile()
这个函数也可以用来编码解决这个问题。在这种情况下,我们只需要处理循环直到满足条件并增加计数器。如果它匹配列表长度,则所有元素都满足该条件。
# Python3 code to demonstrate working of
# Check if all elements in list follow a condition
# Using itertools.takewhile()
import itertools
# initializing list
test_list = [4, 5, 8, 9, 10]
# printing list
print("The original list : " + str(test_list))
# Check if all elements in list follow a condition
# Using itertools.takewhile()
count = 0
for ele in itertools.takewhile(lambda x: x > 3, test_list):
count = count + 1
res = count == len(test_list)
# Printing result
print("Are all elements greater than 3 ? : " + str(res))
输出 :
The original list : [4, 5, 8, 9, 10]
Are all elements greater than 3 ? : True