Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert boolean to integer location in python [duplicate]

Tags:

python

I have a boolean list, say:

x = [True, False, False, True]

How do you convert this list to integer locations, so that you get the result:

y = [1, 4]

?

like image 786
J4y Avatar asked Nov 28 '22 22:11

J4y


2 Answers

You could use a list comprehension in combination with the enumerate function, for example:

>>> x = [True, False, False, True]
>>> [index for index, element in enumerate(x, start=1) if element]
[1, 4]

Alternatively, if you're willing to use NumPy and get a result of type numpy.ndarray, there's a NumPy function that (almost) does what you need: numpy.where.

>>> import numpy
>>> numpy.where(x)
(array([0, 3]),)
>>> numpy.where(x)[0] + 1
array([1, 4])

The strange [0] in the line above is there because numpy.where always returns its results in a tuple: one element of the tuple for each dimension of the input array. Since in this case the input array is one-dimensional, we don't really care about the outer tuple structure, so we use the [0] indexing operation to pull out the actual array we need. The + 1 is there to get from Python / NumPy's standard 0-based indexing to the 1-based indexing that it looks as though you want here.

If you're working with large input data (and especially if the input list is already in the form of a NumPy array), the NumPy solution is likely to be significantly faster than the list comprehension.

like image 180
Mark Dickinson Avatar answered Dec 05 '22 04:12

Mark Dickinson


Use enumerate within a list comprehension:

>>> [i for i, j in enumerate(x, 1) if j]
[1, 4]
like image 21
Mazdak Avatar answered Dec 05 '22 03:12

Mazdak