[Tutor] Finding Match in nexted tuple
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'
> > 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
> ("C") code - so must not be too much, I bet.
> Thank you Magnus.
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',),
[('84536',), ('85003',), ('85004',), ('85006',), ('85007',), ('85008',)]
# no way with list() !
# one solution :
>>> def QueryResultToList(t) :
for item in t :
>>> zips = QueryResultToList(zip_list)
['84536', '85003', '85004', '85006', '85007', '85008']
>>> '85004' in zips
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
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 :
I hope both of these solutions are pythonesque ! (they're really my coding
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 :
More information about the Tutor