移除3个超过3个声纳的巢

时间:2017-07-20 10:12:00

标签: python

我有一个像下面的字符串

line="10,20,30,40,100-200,500,1000-10000"

迭代列表中的每个值并检查是否介于最小值和最大值之间,如果不是则返回False

当前代码看起来像

for i in line.strip().split(','):
        if '-' not in i:
            if not 0 <= int(i) <= 50000:
                return False
        elif len(i.split('-')) == 2:
            for value in i.split('-'):
                if not 0<= int(value) <= 50000:
                    return False
        else:
            return False
    return True

我需要更好地优化它以删除嵌套的if语句和更多的return语句。

违规:

  

重构此代码不会超过3&#34;如果&#34;,&#34;对于&#34;,&#34;而&#34;,&#34;尝试&#34;   和#34;与&#34;语句。

我试图提取不同的方法,但是对于某些排列并没有起作用。 感谢

3 个答案:

答案 0 :(得分:0)

您可以使用生成器表达式替换内部for

for i in list.strip().split(','):
        if '-' not in i:
            if not 0 <= int(i) <= 50000:
                return False
        elif len(i.split('-')) == 2:
            return all(0 <= int(value) <= 50000 for value in i.split('-'))
        else:
            return False
    return True

答案 1 :(得分:0)

你可以组合前两个if,并摆脱第二个for周期,因为你只迭代了两个元素。也不应该{for} return True在for循环之外。使用当前代码,它只检查第一个整数后将返回True(我不确定这是否是你想要的)

for i in line.strip().split(','):
        if '-' not in i and not 0 <= int(i) <= 50000:
            return False
        elif '-' in i and len(i.split('-')) == 2 and not (0<= i.split('-')[0] <= 50000 and 0<= i.split('-')[1] <= 50000):
            return False
        else:
            return False
    return True

答案 2 :(得分:0)

可以通过以下方式实现一些嵌套减少:

for i in line.strip().split(','):
    if '-' not in i:
        return 0 <= int(i) <= 50000

    # The following will fail if there are more than one hyphen
    # if a different error should be thrown, try-catch it
    str_val1, str_val2 = i.split('-')
    value1, value2 = int(str_val1), int(str_val2)

    return 0 <= value1 <= value2 <= 50000