Python - 在列表推导中应用多个条件输出

时间:2016-08-24 04:50:01

标签: python if-statement list-comprehension multiple-conditions

当我遇到一个我无法弄清楚如何做的问题时,我一直在用Python编写RGB到Hex函数的代码。 这是功能本身:

def rgb(r, g, b):
    return ''.join([format("{0:x}".format(x).rjust(2, "0").upper()) if int(x) >= 0 else "00" if int(x) <= 255 else "FF" for x in [r,g,b]])

重要的部分: if int(x)&gt; = 0 else“00”if int(x)&lt; = 255 else“FF”

我希望能够做的是,如果数字小于0或高于255,则应用不同的输出。只有第一个有效,第二个被忽略。我们如何在列表理解中正确地完成多个条件?

2 个答案:

答案 0 :(得分:2)

您当前的... if ... else ...条款没有多大意义:

format("{0:x}".format(x).rjust(2, "0").upper()) if int(x) >= 0 else "00" if int(x) <= 255 else "FF"

表示:

  • format(...) if int(x) >= 0
  • 否则,如果int(x) < 0,那么

    • 00如果int(x) <= 255但已经小于零,那么必须小于255 );
    • else FF

据推测,你的意思是:

"FF" if int(x) > 255 else ("00" if int(x) < 0 else format(...))

但可以肯定的是,使用标准的max-min构造不是更容易吗?

"{0:02X}".format(max(0, min(int(x), 255)))

请注意,这里我们在格式说明符本身(02X

中执行零填充和上部大小写

答案 1 :(得分:-1)

这是你当前的if-else语句,分解为一个函数。从这里可以清楚地看出问题所在。

def broken_if_statement(x):
    if int(x) >= 0:
        # Print value as UPPERCASE hexadecimal.
        return format("{0:x}".format(x).rjust(2, "0").upper())
    else if int(x) <= 255:
        # This code path can only be reached if x < 0!
        return "00"
    else:
        # This code path can never be reached!
        return "FF"

这是编写函数的一种更简单的方法。

def rgb(r, g, b):
    return ''.join([('00' if x < 0
                     else 'FF' if x > 255
                     else "{0:02X}".format(x))
                        for x in (r,g,b) ])

>>> rgb(-10, 45, 300)
'002DFF'

编辑:我原创解释&#34;应用不同的输出&#34;意思是你想要输入小于零,输入等于零,例如&f;对于255但是&#39; FF&#39;对于&gt; 255,因此上面的结构支持它。但是如果&lt; 0和= 0应该导致相同的输出,同样对于&gt; 255和= 255,那么使用min和max限制输入就更简单了。

def rgb(r, g, b):
    return "".join("{0:02X}".format(min(255,max(0,x))) for x in (r,g,b))