I'm getting SyntaxError: invalid syntax
on the following list comprehension:
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]
I don't understand if it's because of the indentation or because i added if.. and
statements; i tried to remove those and
but i still got the error. How can i fix it?
You may use else
for each if
you use
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]
A method would be more readable
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]
The reason you get the error is that a list comprehension has the syntax:
[<value expression> for <target> in <iterator> if <condition>]
or
[<value expression> for <target> in <iterator>]
You can't build a list comprehension like you have done, with multiple values in the way you need. The way I would do it would be to have a function that returns the right color tuple for a given x value:
def color_for_x(x):
...
and then write your comprehension like this:
color = [color_for_x(x) for x in WallData.Qty]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.