问题描述
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
]
另外,不要在生产代码中使用这样的一行!