【问题标题】:Python - Applying multiple conditions output in list comprehensionPython - 在列表理解中应用多个条件输出
【发布时间】:2016-08-24 04:50:01
【问题描述】:

当我遇到一个我无法弄清楚如何做的问题时,我一直在尝试在 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) >= 0 else "00" if int(x)

如果数字低于 0 或高于 255,我想要做的是应用不同的输出。只有第一个有效,第二个被忽略。我们如何正确地在列表推导中执行多个条件?

【问题讨论】:

  • 只需将您的逻辑包装在一个函数中,然后在您的列表理解中使用该函数。

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


【解决方案1】:

您当前的... 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) &gt;= 0
  • 否则,如果int(x) &lt; 0,那么

    • 00 if int(x) &lt;= 255但它已经小于零,所以必须小于 255);
    • 否则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)

【讨论】:

  • @Evert OP 的(不必要的复杂)表达式format("{0:x}".format(x).rjust(2, "0").upper()) 将返回FF 用于25500 用于0
  • 这正是我所需要的。我也不知道格式说明符 {0:02X}。知道真的很酷。非常感谢。
【解决方案2】:

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

编辑:我最初将“应用不同的输出”解释为意味着您希望小于零的输入不同于等于零的输入,例如 'ff' 表示 255 而 'FF' 表示 >255,因此上面的结构支持这一点。但是如果 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))

【讨论】:

    猜你喜欢
    • 2012-05-03
    • 2020-08-27
    • 1970-01-01
    • 2019-07-13
    • 2023-02-14
    • 1970-01-01
    • 2021-12-08
    • 2016-04-21
    • 2017-03-20
    相关资源
    最近更新 更多