I wanted to convert the below code into list comprehension.
for i in list:
if i>b:
i=5
else:
i=0
I tried to use [i if i>b 5 else 0 for i in a]
but it resulted in a syntax error. I have also tried [i for i in a if i>b 5 else 0]
but that too resulted in a syntax error.
Any solutions?
CodePudding user response:
Your attempt:
[i if i>b 5 else 0 for i in a]
Is close, you just want to give 5
not i
like so:
[5 if i>b else 0 for i in a]
Test code:
a = [1,2,3,4,5,6,7,8,9,10]
b = 3
output = [5 if i>b else 0 for i in a]
print(output)
Output:
[0, 0, 0, 5, 5, 5, 5, 5, 5, 5]
This works because the item before the if
is given when the statement evaluates to True
and the value after the else
is given otherwise. So:
output = NumberIfTrue if LogicStatement else NumberIfFalse
is equivalent to :
if LogicStatement:
output = NumberIfTrue
else:
output = NumberIfFalse
In your case:
LogicStatement = i>b
NumberIfTrue = 5
NumberIfFalse = 0
Thus you need (as shown above):
5 if i>b else 0
Then you want to apply this to every item in a list which adds:
for i in a
like so:
5 if i>b else 0 for i in a
This is now a generator, since you want a list, you have to surround the generator with []
brackets so that it "generates" the list with the values you want. So just:
[5 if i>b else 0 for i in a]
Then to get the final solution we just assign the result to output
so it can be used again:
output = [5 if i>b else 0 for i in a]
CodePudding user response:
In your version
[i if i>b 5 else 0 for i in list]
The syntax error is right after the i>b. You have the "true value" there, it is in the wrong place. Riffing on your original code
for i in list:
if i>b: #condition
i=5 #true action
else:
i=0 #false action
The real answer is
[5 if i > b else 0 for i in list]
the pseudo code version
[<true action> if <condition> else <false action> for i in list]