I see list has index member, but is there an index function that applies to
any sequence type?
Like this?
def find_index(seq, value):
try:
find_index = seq.index
except AttributeError:
def find_index(valu e):
for i,v in enumerate(seq):
if v == value: return i
raise ValueError("ind ex(seq, x): x not in sequence")
return find_index(valu e)
I see list has index member, but is there an index function that applies
to any sequence type?
>
If not, shouldn't there be?
Looks like an oversight to me as well, yes. The only "difficult"
implementation would be the one for xrange, because you can't search but
must compute the result - but that should be trivial.
def find_index(seq, value):
try:
find_index = seq.index
except AttributeError:
def find_index(valu e):
for i,v in enumerate(seq):
if v == value: return i
raise ValueError("ind ex(seq, x): x not in sequence")
return find_index(valu e)
>
It doesn't seem like a great idea to do operations like that on
mutable iterators. But if you must:
from itertools import dropwhile
def find_index(seq, value):
a = dropwhile (lambda x: x[1] != value, enumerate(seq))
return a.next()[0]
seems more direct. I think it will raises StopIteration if the value
is not found.
En Thu, 07 Feb 2008 11:31:44 -0200, Diez B. Roggisch <deets@nospam.w eb.de>
escribió:
>I see list has index member, but is there an index function that applies
>to any sequence type?
>>
>If not, shouldn't there be?
>
Looks like an oversight to me as well, yes. The only "difficult"
implementation would be the one for xrange, because you can't search but
must compute the result - but that should be trivial.
xrange is iterable, but not a sequence. Tuples are worse: they implement
__contains__ but not index. So you can say:
py2 in (1,2,4,8)
True
but not:
py(1,2,4,8).ind ex(2)
Given that to implement __contains__ it has to scan the values the same
way as index would do, it's like a tuple saying: "I know where that item
is, and you know that I know that, but I won't tell you!" - rather
frustrating.
En Thu, 07 Feb 2008 20:13:00 -0200, Raymond Hettinger <python@rcn.com >
escribió:
On Feb 7, 1:57 pm, "Gabriel Genellina" <gagsl-...@yahoo.com.a rwrote:
>Tuples are worse: they implement
>__contains__ but not index. So you can say:
>>
>py2 in (1,2,4,8)
>True
>>
>but not:
>>
>py(1,2,4,8).in dex(2)
>
You must be using an old version of Python like 2.5 ;-)
>
As of yesterday, Py2.6 has tuple.index() and tuple.count().
>
Python 2.6a0 (trunk:60638M, Feb 6 2008, 18:10:45)
[GCC 4.1.1 (Gentoo 4.1.1)] on linux2
Comment