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"
To find index of the first occurrence of an element in a given Python List, you can use index() method of List class with the element passed as argument. The index() method returns an integer that represents the index of first match of specified element in the List.
ArrayList. indexOf(). This method returns the index of the first occurance of the element that is specified. If the element is not available in the ArrayList, then this method returns -1.
Use enumerate
, list.index
returns the index of first match found.
>>> t = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False] >>> [i for i, x in enumerate(t) if x] [4, 5, 7]
For huge lists, it'd be better to use itertools.compress
:
>>> from itertools import compress >>> list(compress(xrange(len(t)), t)) [4, 5, 7] >>> t = t*1000 >>> %timeit [i for i, x in enumerate(t) if x] 100 loops, best of 3: 2.55 ms per loop >>> %timeit list(compress(xrange(len(t)), t)) 1000 loops, best of 3: 696 µs per loop
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With