微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

列表推导式中的 Elif 语句

如何解决列表推导式中的 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
]

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?