Given the list
a = [6, 3, 0, 0, 1, 0]
What is the best way in Python to return the list
b = [1, 1, 0, 0, 1, 0]
where the 1's in b correspond to the non-zero elements in a. I can think of running a for loop and simply appending onto b, but I'm sure there must be a better way.
For completeness, and since no one else added this answer:
b = map(bool, a)
But it returns Boolean values and not Integers.
b = [int(i != 0) for i in a]
Will give you what you are looking for.
Another way
>>> a = [6, 3, 0, 0, 1, 0]
>>> [cmp(x,0) for x in a]
[1, 1, 0, 0, 1, 0]
Note that cmp(x,0)
returns -1 for negative numbers, so you might want to abs
that.
You can also, depending on your application, work with numpy array representation:
$ import numpy as np
$ a = [6, 3, 0, 0, 1, 0]
$ (np.array(a)!= 0).astype(int)
array([1, 1, 0, 0, 1, 0])
astype(int) is only necessary if you dont't want a boolean representation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With