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 ...
:
lst = range(-5, 5) pos = [x if x > 0 else 0 for x in lst] neg = [x if x < 0 else 0 for x in lst] print(pos) # [0, 0, 0, 0, 0, 0, 1, 2, 3, 4] print(neg) # [-5, -4, -3, -2, -1, 0, 0, 0, 0, 0]
Alternatively, using for
loop:
pos, neg = [], [] for x in lst: if x > 0: pos.append(x) neg.append(0) else: neg.append(x) pos.append(0)
Or, shorter:
pos, neg = [], [] for x in lst: pos.append(max(x, 0)) neg.append(min(x, 0))