By using the zip builtin function you can easily convert a list of lists into a transposed list of tuples. This can be used for easily selecting columns.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | >>> a=[[0,1],[0,1],[0,1]]
>>> print=zip(*a) #passes the lists in a as separate arguments
[(0, 0, 0), (1, 1, 1)]
>>> print zip(*a)[0] #prints the first column
(0, 0, 0)
>>> a=[[0,1],[0,1,2],[0,1]] #lets see what happens when we use a "ragged" list
>>> print zip(*a) # the transpose is truncated to the shortest row
[(0, 0, 0), (1, 1, 1)]
>>> a=[[0,1],[0,1],[0,1],0] #What if there are not only lists in the list
>>> print zip(*a) #This does not work, so watch out for it.
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: zip argument #4 must support iteration
>>> a=[(0,1),(0,1),(0,1)] #Does it work on a list of tuples?
>>> zip(*a) #Yes because a tuple is iterable.
[(0, 0, 0), (1, 1, 1)]
|
This approach can be used if you get data from a database and you easily want to extract a column. Note that the result is always a tuple and not a list. It shouldn't be used as a matrix-transpose. You should use the Numeric, or Numarray module for that. It can be confusing when you first see it.
you can pad the lists to prevent truncation. If you don't want to loose the elements in the longer lists,
you can pad the short ones with the following:
</pre>
... or you can use map to pad automatically ... ... like described in this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410687