I want to know if there's a way in python to do something like that:
a=[1,2,3,4,5]
for e in a:
print e+=[100 if e<4 else 1]
This should print the numbers: 101,102,103,5,6
Thanks in advance
I want to know if there's a way in python to do something like that:
a=[1,2,3,4,5]
for e in a:
print e+=[100 if e<4 else 1]
This should print the numbers: 101,102,103,5,6
Thanks in advance
List comprehension is one way:
a = [1,2,3,4,5]
b = [x+100 if x < 4 else x+1 for x in a]
[100, 102, 103, 5, 6]
Or as thefourtheye suggested:
b = [x + (100 if x < 4 else 1) for x in a]
Now, as to your code, this is the fix:
for e in a:
print e+(100 if e<4 else 1)
You can also do it with map
:
>>> map(lambda s: s+(100 if s < 4 else 1), a)
[101, 102, 103, 5, 6]
Remember if you were in Python3, map
returns a generator, so you have to list
it:
>>> list(map(lambda s: s+(100 if s < 4 else 1), a))
Try out this
>>> a = [1,2,3,4,5]
>>> b = [x+100 if x < 4 else x+1 for x in a]
>>> print b
[101, 102, 103, 5, 6]
>>>