[Tutor] Finding Match in nexted tuple

denis denis.spir at free.fr
Thu Apr 22 06:36:36 EDT 2004


----- Original Message -----
From: Tim Johnson <tim at johnsons-web.com>
To: <tutor at python.org>
Sent: Thursday, April 22, 2004 3:32 AM
Subject: Re: [Tutor] Finding Match in nexted tuple


> * Magnus Lycka <magnus at thinkware.se> [040421 17:04]:
> > Tim Johnson wrote:
> Tim Johnson wrote:
> > Let's say I have a list of zip codes returned from a MySQLdb query
> > zip_code_list = (('84536',), ('85003',), ('85004',), ('85006',),
> >                  ('85007',), ('85008',))
> > # and I want to look for a match for a value like '85004'
<snip>
> > If '85004' might
> > just be in an arbitrary position in a sequence of tuples with
> > more columns than the zip codes, you could for instance do:
> >
> > if '85004' in str(zip_code_list):
> >     print "Found!"
>
>   Eureka! That's what I meant by a 'pythonesque' solution.
>
>   I must ask: what is the overhead in the call to str?
>
>   I presume that str(zip_code_list) is being handled by compiled
binary
>   ("C") code - so must not be too much, I bet.
>
>   Thank you Magnus.
>   tim

I don't know mySQL, especially if that kind of tuple of single value tuples
is its standard query result form. If yes, and i had to work with such
thing, I would write a short function to make simple list out of them :
def ThingsToList :

>>> zip_list=(('84536',), ('85003',), ('85004',), ('85006',),('85007',),
('85008',))
>>> list(zip_list)
[('84536',), ('85003',), ('85004',), ('85006',), ('85007',), ('85008',)]
# no way with list() !

# one solution :
>>> def QueryResultToList(t) :
        l=[]
        for item in t :
            l.append(item[0])
        return l
>>> zips = QueryResultToList(zip_list)
>>> zips
['84536', '85003', '85004', '85006', '85007', '85008']
>>> '85004' in zips
True

This is the most versatile solution, as it then allows you any operation on
your query result, not only searching an element in it, with a simple, one
level, list.
In you only need searching, you may build a more specific function for that
purpose, changes the searched item rather than the query result's structure
:

>>> def FoundInQueryResult(t,s) :
        # tuple is a tuple of single element tuples
        # s is a string, item (below) a single element tuple
        item=(s,) ; print item    # print statement only for test pûrpose
        if item in t :
            return True
        else :
            return False
>>> FoundInQueryResult(zip_list,'85004')
('85004',)
True

I hope both of these solutions are pythonesque ! (they're really my coding
style)

Now, if your needs of processing with such things are really big, you'd
better write a QueryResult class, and implement such function as methods.
This would lead to nicer (my OOP taste) code like this :
zip_list.found('85004')

denis





More information about the Tutor mailing list