【发布时间】:2025-11-24 16:50:01
【问题描述】:
为什么我在这段代码中得到无效的语法:
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 x < 0 for x in _list结尾,这不是任何正确的 Python 语法。我建议你把它分解成更小的有意义的行。 -
你的代码没有可读性所以容易出错
-
“可读性很重要。” > python.org/dev/peps/pep-0020 写一整套条件,不要纠结复杂的东西。
-
@s.k 你能帮我编辑一下吗
-
哪些值没有改变?但无论如何都不要使用这样的列表理解
标签: python list syntax list-comprehension