Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of non-zero elements in a list in Python

Tags:

python

list

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.

like image 689
rwolst Avatar asked May 27 '13 14:05

rwolst


4 Answers

For completeness, and since no one else added this answer:

b = map(bool, a)

But it returns Boolean values and not Integers.

like image 149
Inbar Rose Avatar answered Oct 06 '22 15:10

Inbar Rose


b = [int(i != 0) for i in a]

Will give you what you are looking for.

like image 29
dave Avatar answered Oct 06 '22 15:10

dave


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.

like image 20
Colonel Panic Avatar answered Oct 06 '22 15:10

Colonel Panic


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

like image 1
user1151446 Avatar answered Oct 06 '22 15:10

user1151446