A question about searching with multiple strings
Mike Meyer
mwm at mired.org
Fri Oct 21 16:59:16 EDT 2005
"googleboy" <mynews44 at yahoo.com> writes:
> for item in all_items:
>
> strItem = str(item)
>
> m = re.search(p[i], strItem, flags = re.I)
> if m:
> height = getattr(item, "height")
> length = getattr(item, "length")
> function = getattr(item, "function")
> print "height is %s, length is %s and function is %s" % height,
> length, function
>
>
> This has the limitation of only working over a single search item. I
> want to be able to search over an uncontrollable number of search
> strings because I will have people wanting to search over 2, 3 or even
> (maybe) as many as 5 different things.
>
> I was thinking that I would try to write a function that created a
> sublist of Items if it matched and then run subsequent searches over
> the subsequent search strings using this sublist.
>
> I am not entirely sure how to store this subset of Items in such a way
> that I can make searches over it. I guess I have to initialize a
> variable of type Item, which I can use to add matching Item's to, but
> I have no idea how to do that....(If it was just a list I could say
> "sublist = []", what do I use for self defined classes? I Am also
> usure how to go about creating a function that will accept any number
> of parameters.
>
> Any assistance with these two questions will be greatly appreciated!
Don't use a real list, use an iterator. Inn particular,
itertools.ifilter will take an arbitrary sequence and returns a
sequence of items that a function says to.
for item in ifilter(lambda i: re.search(p[i], str(i), flags = re.I),
all_items):
print "height is %s, length is %s and function is %s" % \
(item.height, item.length, item.function)
The trick is that ifilter returns a sequence, so you can nest them:
for item in filter(filter1, ifilter(filter2, ifilter(filter3, all_items))):
...
<mike
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list