Slice a list of lists?

Emile van Sebille emile at fenx.com
Wed Sep 8 15:51:41 EDT 2010


On 9/8/2010 12:17 PM Andreas Waldenburger said...
> On Wed, 8 Sep 2010 15:11:51 -0400 Benjamin Kaplan
> <benjamin.kaplan at case.edu>  wrote:
>
>> There is no simple way to get [1,4,7] because it is just a list of
>> lists and not an actual matrix. You have to extract the elements
>> yourself.
>>
>> col = []
>> for row in a:
>>      col.append(row[0])
>>
>>
>> You can do this in one line using a list comprehension:
>> [ row[0] for row in a ]
>
> I would suggest this (esp. the list comprehension version) over my
> suggestion of zip(). WAAAYYYY more readable. Apparently I'm getting
> rusty.
>

zip is very handy for inverting rows and cols (x's and y's, whatever)

 >>> a = [(1,2),(3,4),(5,6),(7,8),(9,10)]
 >>> zip(*a)
[(1, 3, 5, 7, 9), (2, 4, 6, 8, 10)]

So, I like zip if you're dealing with a in a matrix-ish manner, and list 
comps for picking selected items out of a list.

Emile






More information about the Python-list mailing list