python - 如何修改 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。
包括任何一个。
解决方案
我认为您不需要创建范围,因为您可以在值之间进行检查以获得解决方案。
下面的代码使用小于和大于运算符来查找元组之间是否存在 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')
推荐阅读
- php - 尽管在我的控制器中定义了路由,但无法重定向到路由 [Symfony]
- mongodb - 无法从 Docker 中的 Flask GET 和 POST 数据到 MongoDB
- powershell - 静默模式下的 ISDeploymentWizard 状态
- python - Python中不止两个变量的相关系数
- entity-framework-core - 创建基于角色的动态授权
- julia - in() 函数或 in 运算符的广播版本?
- tibco-ems - 无法连接到“ems”:错误=11,消息=未连接服务器
- powerbi - 对于在 Toad 中快速运行的同一查询,Power BI 运行速度非常慢
- wordpress - 使用 GA 或 FB Pixel 跟踪联属网络营销转化
- python-3.x - matplotlib 在所有 ImageGrid 轴上打勾