Python|检查元素是否出现范围
有时,在处理数据时,我们可能会遇到一个简单的问题,即我们有元组形式的范围,我们需要检查一个特定的数字是否位于元组建议的任何范围之间。这在竞争性编程中有它的应用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + enumerate()
可以使用上述功能的组合来执行此任务。在这种情况下,我们只需要遍历 list 的每个元素并使用enumerate()
返回元素存在的元组对的索引。
# Python3 code to demonstrate working of
# Check element for range occurrence
# Using loop + enumerate()
# Initializing list
test_list = [(45, 90), (100, 147), (150, 200)]
# printing original list
print("The original list is : " + str(test_list))
# Initializing element
N = 124
# Check element for range occurrence
# Using loop + enumerate()
res = None
for idx in (idx for idx, (sec, fir) in enumerate(test_list) if sec <= N <= fir):
res = idx
# printing result
print("The index of tuple between which element occurs : " + str(res))
输出 :
The original list is : [(45, 90), (100, 147), (150, 200)]
The index of tuple between which element occurs : 1
方法 #2:使用next() + enumerate()
+ 生成器表达式
也可以使用上述功能的组合来执行此任务。在此,我们只是使用next()
进行迭代。其余的一切都执行类似于上面的函数。
# Python3 code to demonstrate working of
# Check element for range occurrence
# Using next() + enumerate() + generator expression
# Initializing list
test_list = [(45, 90), (100, 147), (150, 200)]
# printing original list
print("The original list is : " + str(test_list))
# Initializing element
N = 124
# Check element for range occurrence
# Using next() + enumerate() + generator expression
res = next((idx for idx, (sec, fir) in enumerate(test_list) if sec <= N <= fir), None)
# printing result
print("The index of tuple between which element occurs : " + str(res))
输出 :
The original list is : [(45, 90), (100, 147), (150, 200)]
The index of tuple between which element occurs : 1