Finding values on sequences and .index()

Mike Fletcher mfletch at tpresence.com
Wed Dec 6 14:24:11 EST 2000


The first approach below only works on Python 2.0, but looks cleaner.  It's
the same approach as the second, which works in just about any Python
version.  And yes, neither is really elegant, that's why people were calling
for the "indexing" keyword in for loops and/or list comprehensions :o) (Oh,
sorry for the spelling error in indices, I always do that and was too lazy
to go back and fix it today).

>>> def indicies( sequence, value ):
... 	return [ index for index in xrange(len(sequence)) if
sequence[index]== value]
... 
>>> indicies( a, 1 )
[0, 4, 8, 11]
>>> def indicies2( sequence, value ):
... 	result = []
... 	for index in xrange(len(sequence)):
... 		if sequence[index] == value:
... 			result.append( index )
... 	return result
... 
>>> 
>>> indicies2( a, 1 )
[0, 4, 8, 11]
>>> 


HTH,
Mike

-----Original Message-----
From: rhamorim at my-deja.com [mailto:rhamorim at my-deja.com]
Sent: Wednesday, December 06, 2000 1:15 PM
To: python-list at python.org
Subject: Finding values on sequences and .index()


Hi.

I have a list that may have many ocurrences of the same data. How do I
find the indexes for all ocurrences of it? list.index(value) only works
for the first ocurrence.

I thought of this ugly hack below, but I guess there's an easier way.

a = [1, 2, 3, 4, 1, 5, 6, 7, 1, 8, 9, 1]
b = map(None, a, range(len(a)))

N = 1 #value to be searched

c = filter(lambda x, n=N: x[0]==N, b)
d = map(lambda x: x[1], c) #this is the returned index list

Thanks in advance...

Roberto Amorim


Sent via Deja.com http://www.deja.com/
Before you buy.
-- 
http://www.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list