By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,660 Members | 1,105 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,660 IT Pros & Developers. It's quick & easy.

Determine multiple indices within a list

P: 3
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]
Dec 2 '10 #1

✓ answered by bvdet

Use built-in function enumerate().
Expand|Select|Wrap|Line Numbers
  1. >>> import random
  2. >>> mylist = [random.choice(range(100)) for i in range(10)]
  3. >>> mylist
  4. [76, 28, 54, 8, 99, 29, 23, 33, 62, 0]
  5. >>> [i for i,n in enumerate(mylist) if n > 33]
  6. [0, 2, 4, 8]
  7. >>> 

Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
Use built-in function enumerate().
Expand|Select|Wrap|Line Numbers
  1. >>> import random
  2. >>> mylist = [random.choice(range(100)) for i in range(10)]
  3. >>> mylist
  4. [76, 28, 54, 8, 99, 29, 23, 33, 62, 0]
  5. >>> [i for i,n in enumerate(mylist) if n > 33]
  6. [0, 2, 4, 8]
  7. >>> 
Dec 2 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.