Getting indices of True values in a boolean list

前端 未结 7 1917
不思量自难忘°
不思量自难忘° 2020-12-07 11:52

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

7条回答
  •  时光取名叫无心
    2020-12-07 12:20

    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
    

提交回复
热议问题