Have a look at this short thread on discuss:
https://discuss.python.org/t/searching-array-of-data-objects/4251/1
After I answered that question, it dawned on me that I have probably
written something like that loop, or variations of it, a thousand times:
for obj in somelist:
if comparison(obj, needle):
do_something(obj)
break
and now it's a thousand and one times *wink*
So here's a thought... suppose we gave list.index an optional keyword-
only comparison function? The typical name for those is "pred", as in
predicate. Then the above becomes:
try:
i = somelist.index(needle, pred=comparison)
except ValueError:
pass
else:
do_something(somelist[i])
If you know for sure the search item exists, then you can drop the
try...except...else:
do_something(somelist[somelist.index(needle, pred=comparison)])
If `pred` is missing or None, a standard equality search is performed.
Together with the operator module, this would allow us to perform common
searches at C speed:
# find the first item less than needle
somelist.index(needle, pred=operator.lt)
We can search a sublist efficiently:
# copies the sublist :-(
for obj in somelist[25:95354]:
...
# save memory by inefficiently walking the entire list :-(
for i, obj in enumerate(somelist):
if i < 25: continue
if i >= 95354: break
...
# avoids both wasting memory and wasting time :-)
i = somelist.index(needle, 25, 95354, pred=comparison)
What do you think?
--
Steven
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/NUR43GEEUX6RBSXK3LQZIAU2FIN5HCQL/
Code of Conduct: http://python.org/psf/codeofconduct/