Determine multiple indices within a list

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jacob l
    New Member
    • Dec 2010
    • 3

    Determine multiple indices within a list

    I am trying to return a list of indices for elements within another list that pass some sort of rule (as fast as possible). Currently I am doing:

    Elementspassed=[elem for elem in Mylist if point > elem]

    for x in Elements passed:
    newlist.append( Mylist.index(x) )
    Mylist[Mylist.index(x)]=[]

    I want to incorporate the for loop into the previous line. I am working with extremely large matrices and this current code takes too long. I am interested in the Elementspassed matrix just to be a list of indices in which point>elem rather than the two step process i am taking.

    For example:

    (for points > 33)
    Now: Elementspassed=[34, 35, 34, 52, 51]
    newlist=[0, 3, 4, 5, 6]

    Want: Elementspassed=[0, 3, 4, 5, 6]
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Use built-in function enumerate().
    Code:
    >>> import random
    >>> mylist = [random.choice(range(100)) for i in range(10)]
    >>> mylist
    [76, 28, 54, 8, 99, 29, 23, 33, 62, 0]
    >>> [i for i,n in enumerate(mylist) if n > 33]
    [0, 2, 4, 8]
    >>>

    Comment

    Working...