首页 > 解决方案 > 如何修改 Range 函数中边界值的包含/排除行为?

问题描述

第 1部分: 我有一本字典:

mydict = {'K': {'VAL1': 'apple', 'VAL2': (60, 80)},
          'L': {'VAL1': 'mango', 'VAL2': (90, 100)},
          'M': {'VAL1': 'pears', 'VAL2': (120, 150)}}

rto = tuple(range(60,80))    # works
rto = tuple(range(mydict['K']['VAL2']))
TypeError: range() integer end argument expected, got list.

我该如何完成这项工作,我想遍历字典?

Part2: 假设上面可以工作,我想检查一个值是否在范围内:

my_value = 70        
rto = tuple(range(60,80))
if my_value in rto :
    print("Value is in range")
else:
    print("Value not in range")

# Output:   
# 70- Value is in range  
# 20- Value not in range  
# 60- Value is in range  
# 80- Value not in range  
# (This tells me that the range function includes 60 and excludes 80 from the 
# test)

如何操纵测试的边界条件?意思是:
包括 60 和 80。
排除 60 或 80。
包括任何一个。

标签: pythonpandasdictionarytuplesrange

解决方案


我认为您不需要创建范围,因为您可以在值之间进行检查以获得解决方案。

下面的代码使用小于和大于运算符来查找元组之间是否存在 my_value。让我知道这是否是您的想法。

 for i in [j['VAL2'] for i,j in mydict.items()]:
    if i[0] <= my_value <= i[-1]:
        print(f'{i},{my_value} value is in range')
    else:
        print(f'{i},{my_value} value is not in range')

推荐阅读