使用Python理解列表时出现错误语法错误

2024-04-25 07:20:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我在下面的列表中得到SyntaxError: invalid syntax

colors = [(141, 0, 248, 0.4) if x >= 150 and x < 200
          (0, 244, 248, 0.4) if x >= 200 and x < 400 
          (255, 255, 0, 0.7) if x >= 400 and x < 600 
          (255, 140, 0, 0.8) if x >= 600 else (255, 0, 0, 0.8) for x in myData]

我不明白是因为缩进还是因为我添加了if .. and语句;我试图删除那些and,但还是出现了错误。我怎样才能修好它


2条回答

您可以对使用的每个if使用else

colors = [(141, 0, 248, 0.4) if x >= 150 and x < 200 else 
          (0, 244, 248, 0.4) if x >= 200 and x < 400 else
          (255, 255, 0, 0.7) if x >= 400 and x < 600 else
          (255, 140, 0, 0.8) if x >= 600 else (255, 0, 0, 0.8) for x in WallData.Qty]

一种方法更具可读性

def apply(x):
    if x >= 150 and x < 200 : return 141, 0, 248, 0.4  
    if x >= 200 and x < 400 : return 0, 244, 248, 0.4  
    if x >= 400 and x < 600 : return 255, 255, 0, 0.7 
    if x >= 600 : return 255, 140, 0, 0.8 
    return 255, 0, 0, 0.8

colors = [apply(x) for x in values]

出现错误的原因是列表理解具有以下语法:

[<value expression> for <target> in <iterator> if <condition>]

[<value expression> for <target> in <iterator>]

您不能像以前那样构建一个列表理解,以您需要的方式使用多个值。 我将使用一个函数为给定的x值返回正确的颜色元组:

def color_for_x(x):
    ...

然后写下你的理解如下:

color = [color_for_x(x) for x in WallData.Qty]

相关问题 更多 >