如何解决列表推导式中的 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 举报,一经查实,本站将立刻删除。