简体   繁体   English

检查数字是否在范围列表中并输出值的最优雅的方法

[英]Most elegant way to check if number is in a list of ranges and output a value

What is the best way to code this pythonicly without the use of many if statements? 在不使用许多if语句的情况下,以Python方式对此进行编码的最佳方法是什么?

If I have for example, 3 ranges: 1 to 5 gives 'A' back 6 to 10 gives 'B' back 11 to 15 gives 'C' back 例如,如果我有3个范围:1到5给出'A'返回6到10给出'B'返回11到15给出'C'返回

I want to check if a number is within those ranges then give me the associated value. 我想检查数字是否在这些范围内,然后给我相关的值。

Considered using dictionary of xranges as keys with values. 考虑将xranges字典用作具有值的键。

dic = {xrange(1,5) : 'A',
       xrange(6,10) : 'B',
       xrange(11, 15) : 'C'}

def test(my_num):
    for key, val in dic.items():
        if my_num in key:
            return val

test(8)

Any ideas? 有任何想法吗?

This is an inefficient way to store that data. 这是存储数据的低效率方法。 You can go back and assemble the dic in a different way if possible. 您可以返回并尽可能以其他方式组装dic As an addition, you can rewrite it using a double comprehension. 另外,您可以使用双重理解来重写它。 You don't see those often but it could be appropriate here. 您不会经常看到这些内容,但在这里可能是合适的。

lookup = {
    value: label for range, value in dic.items for value in range
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM