It's more about python list comprehension syntax. I've got a list comprehension that produces list of odd numbers of a given range:
[x for x in range(1, 10) if x % 2]
This makes a filter - I've got a source list, where I remove even numbers (if x % 2
). I'd like to use something like if-then-else here. Following code fails:
>>> [x for x in range(1, 10) if x % 2 else x * 100]
File "<stdin>", line 1
[x for x in range(1, 10) if x % 2 else x * 100]
^
SyntaxError: invalid syntax
There is a python expression like if-else:
1 if 0 is 0 else 3
How to use it inside a list comprehension?
This question is related to
python
list-comprehension
ternary-operator
conditional-operator
You can do that with list comprehension too:
A=[[x*100, x][x % 2 != 0] for x in range(1,11)]
print A
Just another solution, hope some one may like it :
Using: [False, True][Expression]
>>> map(lambda x: [x*100, x][x % 2 != 0], range(1,10))
[1, 200, 3, 400, 5, 600, 7, 800, 9]
>>>
I was able to do this
>>> [x if x % 2 != 0 else x * 100 for x in range(1,10)]
[1, 200, 3, 400, 5, 600, 7, 800, 9]
>>>
[x if x % 2 else x * 100 for x in range(1, 10) ]
Source: Stackoverflow.com