cell and row

Shi Mu samrobertsmith at gmail.com
Tue Oct 25 05:33:30 EDT 2005


In the follwoing code,
Why the result is "'defenestrate', 'window', 'defenestrate', " before
the original list instead of 'defenestrate', 'window', ?

>>> a = ['defenestrate', 'cat', 'window', 'defenestrate']
>>> for x in a[:]:
... 	if len(x) > 4: a.insert(0, x)
... 	
>>> a
['defenestrate', 'window', 'defenestrate', 'defenestrate', 'cat',
'window', 'defenestrate']

On 10/25/05, Fredrik Lundh <fredrik at pythonware.com> wrote:
> Shi Mu wrote:
>
> >I can not understand the use of "cell" and "row" in the code:
> >
> > # convert the matrix to a 1D list
> > matrix = [[13,2,3,4,5],[0,10,6,0,0],[7,0,0,0,9]]
> > items = [cell for row in matrix for cell in row]
> > print items
>
> working through the Python tutorial might be a good idea.  here's the section
> on list comprehensions:
>
> http://docs.python.org/tut/node7.html#SECTION007140000000000000000
>
> and here's the section on for loops:
>
> http://docs.python.org/tut/node6.html#SECTION006200000000000000000
>
> briefly:
>
>    items = [cell for row in matrix for cell in row]
>
> or, slightly edited for clarity:
>
>    items = [(cell)
>        for row in matrix
>            for cell in row]
>
> is the same thing as:
>
>    items = []
>    for row in matrix:
>        for cell in row:
>            items.append(cell)
>
> except that it's a bit shorter, and a bit more efficient.
>
> </F>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list