![](/img/trans.png)
[英]Python: why is multiple list comprehensions seemingly faster than a single for loop with if...elif statements?
[英]Elif statements in list comprehensions
为什么我在这段代码中得到无效的语法:
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
语句中缺少一个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
]
另外,不要在生产代码中使用这样的行!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.