通过循环旧元组创建新元组的更有效方法
More efficient way of creating new tuple by looping over old tuple
当光标悬停在 tkinter canvas 圆角矩形按钮上时,我已经设法调整颜色:
def shade_rgb(rgb):
""" Adjust shade of rgb by 25% (value 64 out of 256)
:param rgb: tuple of red, green, blue integers 0 to 255
:returns: tuple of red, green, blue integers 0 to 255
"""
converted = []
for i in rgb:
if i < 128:
i = i + 64
else:
i = i - 64
converted.append(i)
return tuple(converted)
我看过列表理解和元组生成器的代码,我相信它们会大大缩短代码。但是我可以“理解”如何使它起作用?
回复评论
“你卡在什么地方了?”
我对生成器的尝试是这样的:
return tuple(i = i + 64 if i<128 else i = i - 64 for i in rgb)
通常在 Python 我会使用:
i = i + 64
或:
i += 64
但显然在发电机中,您进入了另一个宇宙,物理规则变为:
i + 64
return (i + 64 if i < 128
else i - 64
for i in rgb)
哪里卡住了?
试试这个:
return tuple([i+64 if i < 128 else i - 64 for i in rgb])
您可以传递 generator expression to the tuple 构造函数。
return tuple(i+64 if i<128 else i-64 for i in rgb)
元组理解没有直接语法,probably because tuples usually contain heterogeneous data, while lists usually contain homogeneous data。
当光标悬停在 tkinter canvas 圆角矩形按钮上时,我已经设法调整颜色:
def shade_rgb(rgb):
""" Adjust shade of rgb by 25% (value 64 out of 256)
:param rgb: tuple of red, green, blue integers 0 to 255
:returns: tuple of red, green, blue integers 0 to 255
"""
converted = []
for i in rgb:
if i < 128:
i = i + 64
else:
i = i - 64
converted.append(i)
return tuple(converted)
我看过列表理解和元组生成器的代码,我相信它们会大大缩短代码。但是我可以“理解”如何使它起作用?
回复评论
“你卡在什么地方了?”
我对生成器的尝试是这样的:
return tuple(i = i + 64 if i<128 else i = i - 64 for i in rgb)
通常在 Python 我会使用:
i = i + 64
或:
i += 64
但显然在发电机中,您进入了另一个宇宙,物理规则变为:
i + 64
return (i + 64 if i < 128
else i - 64
for i in rgb)
哪里卡住了?
试试这个:
return tuple([i+64 if i < 128 else i - 64 for i in rgb])
您可以传递 generator expression to the tuple 构造函数。
return tuple(i+64 if i<128 else i-64 for i in rgb)
元组理解没有直接语法,probably because tuples usually contain heterogeneous data, while lists usually contain homogeneous data。