How to generically transform a list?

John Lenton john at grulic.org.ar
Thu Aug 26 17:04:36 CEST 2004


On Thu, Aug 26, 2004 at 04:50:26PM +0200, Marco Aschwanden 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
> 
> 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.

mm... maybe I'm missing something, but

    >>> theList = [['a',1,11,'aa'], ['b',2,22,'bb'],['c',3,33,'cc']]
    >>> wanted = 2,1
    >>> [[i[j] for j in wanted] for i in theList]
    [[11, 1], [22, 2], [33, 3]]

seems to me to be what you want.


-- 
John Lenton (john at grulic.org.ar) -- Random fortune:
Perro ladrador, poco mordedor. 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20040826/198502f5/attachment.pgp>


More information about the Python-list mailing list