J4y J4y - 1 year ago 270
Python Question

Convert boolean to integer location in 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]


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download