Python - 测试列表中给定范围的所有偶数元素
给定一个元素列表,测试是否所有元素都在一个范围内。
Input : test_list = [3, 1, 4, 6, 8, 10, 1, 9], i, j = 2, 5
Output : True
Explanation : 4, 6, 8, 10, all are even elements in range.
Input : test_list = [3, 1, 4, 6, 87, 10, 1, 9], i, j = 2, 5
Output : False
Explanation : All not even in Range.
方法#1:使用循环
在这种情况下,我们迭代指定范围内的部分列表,即使我们在列表中发现任何奇怪的出现,也标记出列表。
Python3
# Python3 code to demonstrate working of
# Test for all Even elements in List Range
# Using loop
# initializing list
test_list = [3, 1, 4, 6, 8, 10, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 5
res = True
for idx in range(i, j + 1):
# check if any odd
if test_list[idx] % 2 :
res = False
break
# printing result
print("Are all elements even in range : " + str(res))
Python3
# Python3 code to demonstrate working of
# Test for all Even elements in List Range
# Using all() + list comprehension
# initializing list
test_list = [3, 1, 4, 6, 8, 10, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 5
# all() checks for all even elements
res = all(test_list[idx] % 2 == 0 for idx in range(i, j + 1))
# printing result
print("Are all elements even in range : " + str(res))
输出
The original list is : [3, 1, 4, 6, 8, 10, 1, 9]
Are all elements even in range : True
方法#2:使用all() +列表推导式
在这种情况下,使用 all() 检查所有要偶数的元素,并使用列表理解来循环范围内的元素。
蟒蛇3
# Python3 code to demonstrate working of
# Test for all Even elements in List Range
# Using all() + list comprehension
# initializing list
test_list = [3, 1, 4, 6, 8, 10, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 5
# all() checks for all even elements
res = all(test_list[idx] % 2 == 0 for idx in range(i, j + 1))
# printing result
print("Are all elements even in range : " + str(res))
输出
The original list is : [3, 1, 4, 6, 8, 10, 1, 9]
Are all elements even in range : True