[Tutor] quicker .strip?
Lloyd Kvam
pythontutor at venix.com
Fri Jan 9 17:30:11 EST 2004
Stryder wrote:
> Wow, completely surprised by the quick reply, thanks all!
>
(snipped)
> Why the * with zip though? It seems to be necessary to achieve the
> formatting I want, but I didn't notice any direct reference to it in the
> python23 doc.
>
> -Stryder
zip is written to get multiple arguments, each of which is a sequence, e.g.:
zip( (1,2,3), (4,5,6), (7,8,9) )
fetchall would return the above data like so:
( (1,2,3), (4,5,6), (7,8,9) )
embedded in a tuple.
Python as some alternative syntax for passing parameters to functions. If
you have a tuple that contains the positional arguments for a function, passing
the tuple with a preceding * causes the contents of the tuple to be mapped into
the positional args.
Similarly a dictionary passed with ** preceding it will map its contents to the
keyword parameters of a function.
These conventions allow you to easily program cases where the arguments for
functions originate in less conventional ways - such as you've just encountered
with fetchall and zip.
>
> -----Original Message-----
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On
> Behalf Of Lloyd Kvam
> Sent: Friday, January 09, 2004 1:18 PM
> To: firephreek
> Cc: tutor at python.org
> Subject: Re: [Tutor] quicker .strip?
>
>
> fetchall returns a list of lists (well tuples, but you understand).
> Effectively it's a matrix. Your data looks a little funny because each
> row is a single element.
>
> I'd suggest:
>
> ip = cursor.fetchall()
> for x in ip: # row by row
> for alpha in x: # column by column
> config=getConfig(alpha) ##Custom function that uses
> httplib to
>
> There's no need to convert the row to a string and remove the characters
> introduced by the conversion. The IP address is already there as a
> string.
>
> A cute coding trick for this case:
>
> ip_list = zip(*cursor.fetchall())[0]
> for ip in ip_list:
> config =getConfig(ip)
>
> While we usually think of zip as peeling of list members in parallel it
> is actually a matrix transpose function. This converts the fetchall
> results from a list of rows to a list of columns. Your ip addresses are
> the first
> (zeroth) column.
>
> HTH
>
>
> Lloyd Kvam
> Venix Corp.
> 1 Court Street, Suite 378
> Lebanon, NH 03766-1358
>
> voice: 603-653-8139
> fax: 801-459-9582
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice: 603-653-8139
fax: 801-459-9582
More information about the Tutor
mailing list