📜  Python - 在范围内测试 K

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

Python - 在范围内测试 K

给定一个列表,测试给定范围内的所有元素是否都等于 K。

方法 #1:使用any()

在这里,我们检查要找到的逻辑的否定,检查我们是否得到了除 K 之外的任何元素,我们返回真值的否定以获得实际结果。

Python3
# Python3 code to demonstrate working of 
# Test K in Range
# Using any()
  
# initializing list
test_list = [2, 3, 4, 4, 4, 4, 6, 7, 8, 2]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing Range
i, j = 2, 5
  
# initializing K 
K = 4
  
# any() to check if any element other than K present 
# negation gives result 
res = not any(test_list[idx] != K for idx in range(i, j + 1))
  
# printing result 
print("Are all elements in range K ? : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Test K in Range
# Using all() 
  
# initializing list
test_list = [2, 3, 4, 4, 4, 4, 6, 7, 8, 2]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing Range
i, j = 2, 5
  
# initializing K 
K = 4
  
# all() to check all elements to be K 
res = all(test_list[idx] == K for idx in range(i, j + 1))
  
# printing result 
print("Are all elements in range K ? : " + str(res))


输出
The original list is : [2, 3, 4, 4, 4, 4, 6, 7, 8, 2]
Are all elements in range K ? : True

方法 #2:使用 all()

在此,我们使用 all() 检查所需列表范围内的所有元素是否为 K。

蟒蛇3

# Python3 code to demonstrate working of 
# Test K in Range
# Using all() 
  
# initializing list
test_list = [2, 3, 4, 4, 4, 4, 6, 7, 8, 2]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing Range
i, j = 2, 5
  
# initializing K 
K = 4
  
# all() to check all elements to be K 
res = all(test_list[idx] == K for idx in range(i, j + 1))
  
# printing result 
print("Are all elements in range K ? : " + str(res))
输出
The original list is : [2, 3, 4, 4, 4, 4, 6, 7, 8, 2]
Are all elements in range K ? : True