Indentifying the LAST occurrence of an item in a list
John Machin
sjmachin at lexicon.net
Fri Apr 6 20:46:35 EDT 2007
On Apr 7, 9:25 am, "mkPyVS" <mikemine... at hotmail.com> wrote:
> On Apr 5, 6:37 pm, "John Machin" <sjmac... at lexicon.net> wrote:
>
> >>> help(list.index)
> > Help on method_descriptor:
>
> > index(...)
> > L.index(value, [start, [stop]]) -> integer -- return first index
> > of value
>
> > I look forward to your next version.
>
> Great point! I was assuming the temp variable space was static but the
> pointer to the start of the list was moving-> shame on me (what
> language is this now ;)!
Indeed. IMHO every function/method that searches a sequence should
have start/stop arguments so that the caller can search a slice
without actually copying the slice.
>
> Couldn't resist the temptation to just collect all of the locations as
> I traversed
>
> m = [2,9,1,5,6,3,1,1,9,2]
> f = 1 #What we're looking for
> location = 0 #Start at beginning of list
> fIndexs = []
> while 1:
> try:
> location = m.index(f,location) + 1
> fIndexs.append(location-1)
> except ValueError:
> break
>
> print("Last location = %d" % fIndexs[-1])
1. print is a statement, not a function.
2. fIndexs[-1] will crash and burn if there are no occurrences of f in
m.
> print("All Items = %s" % fIndexs)
FWIW, here's my take on a function that emulates the "missing" rindex
method:
8<--- start rindex.py ---
def rindex(seq, value, lo=0, hi=None):
"""If there is an x such that seq[x] == value and lo <= x < hi
return the largest such x, else raise ValueError"""
seqlen = len(seq)
if lo < 0:
lo += seqlen
if lo < 0:
lo = 0
if hi is None:
hi = seqlen
elif hi < 0:
hi += seqlen
if hi < 0:
hi = 0
lo = seq.index(value, lo, hi)
while True:
try:
lo = seq.index(value, lo + 1, hi)
except ValueError:
return lo
if __name__ == "__main__":
import sys
av = sys.argv
print rindex(av[4:], av[1], int(av[2]), int(av[3]))
8<--- end rindex.py ---
Cheers,
John
More information about the Python-list
mailing list