Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting indices of True values in a boolean list

Tags:

python

list

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"

like image 599
Amon Avatar asked Jan 30 '14 05:01

Amon


People also ask

How do you find the index of a specific value in Python?

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.

How do I find the index of a specific element?

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.


2 Answers

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 
like image 197
Ashwini Chaudhary Avatar answered Oct 01 '22 03:10

Ashwini Chaudhary


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]) 
like image 26
jterrace Avatar answered Oct 01 '22 03:10

jterrace