我正在开发一个函数,它允许用户提供一个值列表,然后自动填充if
/elif
块。例如,这里有一个if
/elif
块的示例,我正在尝试使用acres_list
自动填充该块:
acres_list = [15, 20, 25, 35, 45]
if acres <= 15:
return 1
elif 20 >= acres >15:
return 2
elif 25 >= acres > 20:
return 3
elif 35 >= acres > 25:
return 4
elif 45 >= acres > 35:
return 5
elif acres > 45:
return 6
我可以提供一个指向特定列表值的指针,如下所示:
acres = 17.46 # Some value to test. The function should return `2`
acres_list = [15, 20, 25, 35, 45]
def find_acres(acres, acres_list):
if acres <= acres_list[0]:
return 1
elif acres_list[1] >= acres >acres_list[0]:
return 2
elif acres_list[2] >= acres > acres_list[1]:
return 3
elif acres_list[3] >= acres > acres_list[2]:
return 4
elif acres_list[4] >= acres > acres_list[3]:
return 5
elif acres > acres_list[4]:
return 6
但是,如果用户提供以下列表,则此操作将失败:
acres_list = [15, 20, 25, 35, 45, 50, 60, 70, 120]
或
acres_list = [5, 10, 15]
我可以采取什么方法自动填充具有可变大小值列表的if
/else
块
你需要概括这个过程。编写循环以按索引遍历值。返回大于目标
acres
的第一个值的索引这是基本结构。您需要检查这是否适用于小于或大于列表中任何值的值
你能从这里结束吗
还可以查找
enumerate
函数;这将使您的代码变得更好您可以使用对分模块在有序列表中高效搜索位置:
相关问题 更多 >
编程相关推荐