[Python-Dev] find_first (and relatives) (original) (raw)
Josiah Carlson jcarlson at uci.edu
Tue Sep 14 18:58:56 CEST 2004
- Previous message: [Python-Dev] find_first (and relatives)
- Next message: [Python-Dev] httplib is not v6 compatible, is this going to be fixed?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
I was a bit surprised to find out that python doesn't seem to have builtin functors, such as findfirst. Although there are ways to simulate such functions, it would be good to have an expanded set of functional programming tools which are coded in C for speed.
I think I've been here long enough, and it is getting to be my turn to do this kind of thing once, so here it goes...
Address your concerns of "Python should or should not have this thing" on python-list first (available as a newsgroup as comp.lang.python if you so prefer). Python-dev is about developing the core language, not about fielding requests without background, support, salutation, and "thank you for your consideration".
As for "find_first", the first mention of such things I found on the net were the Boost C++ libraries for searching strings. Considering your recent posts on the C++ sig with regards to Boost::Python, this seems like what you were referring to. Searching strings are generally done via "string literal".find("substring literal") or string_variable.find(substring_variable), and any other such variations you would care to use. There also exists a find_all mechanism in the regular expression module re, which comes standard with Python. Lists also include find methods, though they call them index(). If your list is sorted, you may want to consider the bisect module.
If you desire your finding methods to return an iteratble through the sequence of positions of the item, perhaps this little throwaway generator would be sufficient (which I'm sure a python-list user could have helped you with)...
def find_first(str_or_list, item):
if type(str_or_list) in (str, unicode):
f = str_or_list.find(item)
while f != -1:
yield f
f = str_or_list.find(item, f)
elif type(str_or_list) is list:
try:
f = str_or_list.index(item)
except ValueError:
return
while 1:
yield f
try:
f = str_or_list.index(item, f)
except ValueError:
return
else:
raise ValueError,
"type %s is not supported for searching"%type(str_or_list)
- Josiah
- Previous message: [Python-Dev] find_first (and relatives)
- Next message: [Python-Dev] httplib is not v6 compatible, is this going to be fixed?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]