使用比较时如何简化log if/elif语句
How to simplify long if/elif statement when using comparasion
我正在尝试简化这个:
if num < 9:
y = 1
elif num < 17:
y = 2
elif num < 25:
y = 3
elif num < 33:
y = 4
elif num < 41:
y = 5
elif num < 49:
y = 6
elif num < 57:
y = 7
else:
y = 8
我还没有找到方法 - 有人可以帮我吗?
我想到的唯一想法是创建一个以范围作为键的字典。
ranges = {range(0,9):1,range(9,17):2,range(17,25):3,range(25,33):4,range(33,41):5,range(41,49):6,range(49,57):7}
number = 10
for k,v in ranges.items():
if number in k:
print(v)
在这种情况下,输出是 2
尝试枚举?
num=32
x=[9,17,25,33,41,48,57]
for nums,data in enumerate(x):
if data>num:
y=nums+1
break
else:
pass
print(y)
跨越一组已排序的任意边界可以通过以下方式完成:
all_bounds = [9,17,25,33,41,49,57]
y = len(all_bounds) + 1 # case when all tests fail
for ix, bound in enumerate(all_bounds):
if num < bound:
y = ix + 1
break
如评论中所述,如果有关于如何得出边界的规则,那么最好使用它 - 但前提是它是一个明确的规则,最好对它的产生有一定的了解。不要在任意数据上强行拟合模式。
对于大量的边界值,我会用二分法搜索正确的值;对于这个例子,这是不值得的。
您可以像这样遍历条件:
num = 32
limits = (57, 49, 41, 33, 25, 17, 9,)
# ^ traversing in reverse because then
# the chance that we don't have to go
# through the entire loop is greater.
for possible_y, limit in zip(range(7, 0, -1), limits):
# zip takes 2 or more iterables and returns
# tuples of the current iteration for each iterable
# so e.g (7, 57,) is returned for the first iteration.
if num < limit:
y = possible_y
break
else:
# else after a for loop in Python is only executed if
# no break statement was encountered in the outer-
# most loop.
y = 8
我正在尝试简化这个:
if num < 9:
y = 1
elif num < 17:
y = 2
elif num < 25:
y = 3
elif num < 33:
y = 4
elif num < 41:
y = 5
elif num < 49:
y = 6
elif num < 57:
y = 7
else:
y = 8
我还没有找到方法 - 有人可以帮我吗?
我想到的唯一想法是创建一个以范围作为键的字典。
ranges = {range(0,9):1,range(9,17):2,range(17,25):3,range(25,33):4,range(33,41):5,range(41,49):6,range(49,57):7}
number = 10
for k,v in ranges.items():
if number in k:
print(v)
在这种情况下,输出是 2
尝试枚举?
num=32
x=[9,17,25,33,41,48,57]
for nums,data in enumerate(x):
if data>num:
y=nums+1
break
else:
pass
print(y)
跨越一组已排序的任意边界可以通过以下方式完成:
all_bounds = [9,17,25,33,41,49,57]
y = len(all_bounds) + 1 # case when all tests fail
for ix, bound in enumerate(all_bounds):
if num < bound:
y = ix + 1
break
如评论中所述,如果有关于如何得出边界的规则,那么最好使用它 - 但前提是它是一个明确的规则,最好对它的产生有一定的了解。不要在任意数据上强行拟合模式。
对于大量的边界值,我会用二分法搜索正确的值;对于这个例子,这是不值得的。
您可以像这样遍历条件:
num = 32
limits = (57, 49, 41, 33, 25, 17, 9,)
# ^ traversing in reverse because then
# the chance that we don't have to go
# through the entire loop is greater.
for possible_y, limit in zip(range(7, 0, -1), limits):
# zip takes 2 or more iterables and returns
# tuples of the current iteration for each iterable
# so e.g (7, 57,) is returned for the first iteration.
if num < limit:
y = possible_y
break
else:
# else after a for loop in Python is only executed if
# no break statement was encountered in the outer-
# most loop.
y = 8