列表推导式中的 Elif 语句

问题描述

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

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,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"

解决方法

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

_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
]

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...