in Python I have a list with 96 entries, some are positiv, some are negative. I now want to new lists with 96 entries each. The first one should include all positiv values and instead of the negative values it should be 0 at this place in the list. The same the other way round for the second one. I think I have to use list-comprehension but don´t know how…
Thanks for help!
Advertisement
Answer
Here’s one way to do it, using list comprehensions and ... if ... else ...
:
JavaScript
x
8
1
lst = range(-5, 5)
2
3
pos = [x if x > 0 else 0 for x in lst]
4
neg = [x if x < 0 else 0 for x in lst]
5
6
print(pos) # [0, 0, 0, 0, 0, 0, 1, 2, 3, 4]
7
print(neg) # [-5, -4, -3, -2, -1, 0, 0, 0, 0, 0]
8
Alternatively, using for
loop:
JavaScript
1
9
1
pos, neg = [], []
2
for x in lst:
3
if x > 0:
4
pos.append(x)
5
neg.append(0)
6
else:
7
neg.append(x)
8
pos.append(0)
9
Or, shorter:
JavaScript
1
5
1
pos, neg = [], []
2
for x in lst:
3
pos.append(max(x, 0))
4
neg.append(min(x, 0))
5