Explanation about for

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Tue Jan 10 10:22:18 EST 2012


Am 10.01.2012 12:37 schrieb Νικόλαος Κούρας:

> So that means that
>
> for host, hits, agent, date in dataset:
>
> is:
>
> for host, hits, agent, date in  (foo,7,IE6,1/1/11)
>
> and then:
>
> for host, hits, agent, date in  (bar,42,Firefox,2/2/10)
>
> and then:
>
> for host, hits, agent, date in  (baz,4,Chrome,3/3/09)

No.

As said, dataset is the whole result set. For now, you can see it as a 
list of all rows (which you get if you do l=list(dataset)).

Let's assume you have your data in a list now, which is equivalent 
concerning the iteration.

Then you have something like

dataset = [
     ('foo',7,'IE6','1/1/11'),
     ('bar',42,'Firefox','2/2/10'),
     ('baz',4,'Chrome','3/3/09')
]


Doing

for row in dataset: print row

is equivalent to

row = ('foo',7,'IE6','1/1/11')
print row

row = ('bar',42,'Firefox','2/2/10')
print row

row = ('baz',4,'Chrome','3/3/09')
print row



Doing

for a, b, c, d in dataset:
     do_funny_stuff(a, d, c, b)

is

a, b, c, d = ('foo',7,'IE6','1/1/11');
# which is the same as
# a = 'foo'; b = 7; c = 'IE6'; d = '1/1/11';
do_funny_stuff(a, d, c, b)

a, b, c, d = ('bar',42,'Firefox','2/2/10')
do_funny_stuff(a, d, c, b)

a, b, c, d = ('baz',4,'Chrome','3/3/09')
do_funny_stuff(a, d, c, b)


The "body" of the for suite is executed once for each element.

You have read already

http://docs.python.org/tutorial/controlflow.html#for-statements
http://docs.python.org/library/stdtypes.html#iterator-types

?


Thomas



More information about the Python-list mailing list