How to generically transform a list?
Daniel Yoo
dyoo at hkn.eecs.berkeley.edu
Thu Aug 26 14:35:18 EDT 2004
Marco Aschwanden <PPNTWIMBXFFC at spammotel.com> wrote:
: Suppose you have a list of lists:
: theList = [['a',1,11,'aa'], ['b',2,22,'bb'],['c',3,33,'cc']]
: I would like to have a GENERIC way how to turn this list of list into
: another list of list.
: - A user can choose which columns she wants
: - A user can select the order of the columns
It sounds like you want something like the 'cut' Unix command. Here's
one way to do it.
###
def cut(iterable, columns):
"""Selects columns from the iterable."""
for row in iter(iterable):
yield(tuple([row[i] for i in columns]))
###
For example:
###
>>> l = [['1', '2', '3'],
... ['a', 'b', 'c'],
... ['ka', 'na', 'da']]
>>>
>>> for row in cut(l, (2, 0, 1)): print row
...
('3', '1', '2')
('c', 'a', 'b')
('da', 'ka', 'na')
>>>
>>> for row in cut(l, (2, 1)): print row
...
('3', '2')
('c', 'b')
('da', 'na')
###
Hope this helps!
More information about the Python-list
mailing list