Python - 在列表理解中应用多个条件输出

Python - Applying multiple conditions output in list comprehension

我一直在尝试在 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]])

重要部分: 如果 int(x) >= 0 否则 "00" 如果 int(x) <= 255 否则 "FF"

我想做的是在数字小于 0 或大于 255 时应用不同的输出。只有第一个有效,第二个被忽略。我们如何在列表理解中正确地做多个条件?

您当前的 ... if ... else ... 子句没有多大意义:

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

表示:

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

    • 00 if int(x) <= 255但是它已经小于零所以必须小于 255);
    • 其他FF

大概你想拥有:

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

但是可以肯定的是,使用标准的最大-最小结构不是更容易吗?

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

请注意,这里我们在格式说明符本身中进行零填充和大写 (02X)

这是您当前的 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'

编辑:我最初将 "apply a different output" 解释为您希望小于零的输入与等于零的输入不同,例如 'ff' 表示 255,但 'FF' 表示 >255 ,因此上面的结构支持它。但是如果 <0 和 =0 应该产生相同的输出,同样对于 >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))