【问题标题】:Elif statements in list comprehensions列表推导中的 Elif 语句
【发布时间】:2025-11-24 16:50:01
【问题描述】:

为什么我在这段代码中得到无效的语法:

def rgb(r, g, b):
    _list = []
    _list.append(r)
    _list.append(g)
    _list.append(b)
    _list = [hex(x).replace("x", "") if len(str(x)) == 1 and x >= 0 and x <= 255 else hex(x).replace("0", "").replace("x", "").upper() if len(str(x)) > 1 else hex(255) if x > 255 else hex(0) if x < 0  for x in _list]
    return ''.join(_list)

我按照人们的建议编辑了我的代码,你能解释一下为什么我的值在列表中没有改变

def rgb(r, g, b):
    _list = []
    _list.append(r)
    _list.append(g)
    _list.append(b)
    for x in _list:
        if len(str(x)) == 1:
            x = hex(x).replace("x", "")
        elif len(str(x)) > 1 and x >= 0 and x <= 255:
            x = hex(x).replace("x", "").replace("0", "").upper()
        elif x <= 0 :
            x = hex(0)
        elif x >= 255:
            x = hex(255)
    return ''.join(_list)

rgb(-20, 275, 125) #期望结果 = "00FF7D"

【问题讨论】:

  • 列表理解中的代码没有意义。它以 if x &lt; 0 for x in _list 结尾,这不是任何正确的 Python 语法。我建议你把它分解成更小的有意义的行。
  • 你的代码没有可读性所以容易出错
  • “可读性很重要。” > python.org/dev/peps/pep-0020 写一整套条件,不要纠结复杂的东西。
  • @s.k 你能帮我编辑一下吗
  • 哪些值没有改变?但无论如何都不要使用这样的列表理解

标签: python list syntax list-comprehension


【解决方案1】:

您在最后的嵌套if 语句中缺少一个else ""。像这样,它可以工作,但不能达到预期的结果。

_list = [
  (
    hex(x).replace("x", "")
    if len(str(x)) == 1 and x >= 0 and x <= 255
    else (
      hex(x).replace("0", "").replace("x", "").upper()
      if len(str(x)) > 1 
      else (
        hex(255)
        if x > 255
        else (
          hex(0) if x < 0 else ""  # <- here!
        )
      )
    )
  )
  for x in _list
]

另外,不要在生产代码中使用这样的行!

【讨论】:

  • 好的,我编辑了我的东西,但为什么这里的值没有改变,你能帮忙