[Tutor] List madness

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 7 Mar 2002 10:33:47 -0800 (PST)


On Thu, 7 Mar 2002 Doug.Shawhan@gecits.ge.com wrote:

> >>> for each in pungent:
> 	thing = re.findall('Briggs', each)
> 	if thing != []:
> 		print each

> def findit(db, item):
> 	for each in db:
> 		thing = re.findall(item, '%s'%each)
> 		if thing != [] : return each 
> 		else:
> 			return '%s not found, chump.'%item

As you've noticed, there's some wackiness involved with that 'else'
statement.  I think you meant to return '%s not found, chump' only after
all of items in 'db' have been checked.

It's like having a row of cookie jars, and after looking into the first
one, we want to continue looking at the rest of the cookie jars, even if
the first is just filled with crumbs --- we don't want to give up so fast!

###
def findit(db, item):
    for each in db:
        thing = re.findall(item, '%s'%each)
        if thing != [] : return each 
    return '%s not found, chump.'%item
###

Otherwise, we prematurely report that we couldn't find anything, even
though we've only looked at the first element in db.


If we want to collect all the cookies from all the jars and bring them all
together, we can keep a sack and just stuff in anything we can find:

###
def findAllIts(db, item):
    sack = []
    for each in db:
        sack.extend(re.findall(item, '%s' % each))
    return sack
###


Good luck!