I have a piece of my code where I'm supposed to create a switchboard. I want to return a list of all the switches that are on. Here "on" will equal True
and "off" equal False
. So now I just want to return a list of all the True
values and their position. This is all I have but it only return the position of the first occurrence of True
(this is just a portion of my code):
self.states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
def which_switch(self):
x = [self.states.index(i) for i in self.states if i == True]
This only returns "4"
TL; DR: use np.where
as it is the fastest option. Your options are np.where
, itertools.compress
, and list comprehension
.
See the detailed comparison below, where it can be seen np.where
outperforms both itertools.compress
and also list comprehension
.
>>> from itertools import compress
>>> import numpy as np
>>> t = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]`
>>> t = 1000*t
list comprehension
>>> %timeit [i for i, x in enumerate(t) if x]
457 µs ± 1.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
itertools.compress
>>> %timeit list(compress(range(len(t)), t))
210 µs ± 704 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
numpy.where
>>> %timeit np.where(t)
179 µs ± 593 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
You can use filter for it:
filter(lambda x: self.states[x], range(len(self.states)))
The range
here enumerates elements of your list and since we want only those where self.states
is True
, we are applying a filter based on this condition.
For Python > 3.0:
list(filter(lambda x: self.states[x], range(len(self.states))))
Using element-wise multiplication and a set:
>>> states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> set(multiply(states,range(1,len(states)+1))-1).difference({-1})
Output:
{4, 5, 7}
If you have numpy available:
>>> import numpy as np
>>> states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> np.where(states)[0]
array([4, 5, 7])
Simply do this:
def which_index(self):
return [
i for i in range(len(self.states))
if self.states[i] == True
]
Use dictionary comprehension way,
x = {k:v for k,v in enumerate(states) if v == True}
Input:
states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
Output:
{4: True, 5: True, 7: True}
Source: Stackoverflow.com