How to generically transform a list?

Neal Holtz nholtz at docuweb.ca
Thu Aug 26 18:08:54 EDT 2004


Marco Aschwanden <PPNTWIMBXFFC at spammotel.com> wrote in message news:<mailman.2429.1093531645.5135.python-list at python.org>...
> 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
> 
> For example:
> The user wants columns: 1,2
> The user wants it to be ordered: 2,1
> 
> A non generic approach would maybe do the following:
> 
> >>> theList = [['a',1,11,'aa'], ['b',2,22,'bb'],['c',3,33,'cc']]
> >>> new_list = [[row[2], row[1]] for row in theList]
> >>> new_list
> [[11, 1], [22, 2], [33, 3]]
> 
> I am sure there must be a rather elegant generic approach, which is 
> lurking somewhere to be realeased.
> 
> Thanks for any hint in advance,
> Marco

theList = [['a',1,11,'aa'], ['b',2,22,'bb'],['c',3,33,'cc']]
cols = [2,1]
new_list = [[row[i] for i in cols] for row in theList]
new_list
[[11, 1], [22, 2], [33, 3]]

?



More information about the Python-list mailing list