Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function to find indexes of 1s in binary array and

Tags:

python

numpy

I have an array which looks like this

[1, 0, 1 , 0 , 0, 1]

And I want to get those indexes that have 1 in it. So here I would get an array of [0, 2 , 5] and then based on it I would create a new array that takes these numbers and exponantiate 2 with them So the end array is

[2**0, 2**2, 2**5]

Is there a way to write it as shortly as possible?

like image 797
Alex T Avatar asked Jan 04 '23 02:01

Alex T


1 Answers

you could use enumerate in a list comprehension:

a = [1, 0, 1 , 0 , 0, 1]
b = [2**idx for idx, v in enumerate(a) if v]
b

output:

[1, 4, 32]
like image 188
Reblochon Masque Avatar answered Feb 21 '23 05:02

Reblochon Masque