Howto: extract a 'column' from a list of lists into a new list?

Bengt Richter bokr at oz.net
Tue Jul 1 16:07:43 EDT 2003


On Tue, 01 Jul 2003 10:03:11 +0200, Max M <maxm at mxm.dk> wrote:

>Greg Brunet wrote:
>
>> but I'm not sure about how to do that.  I can do this:
>> 
>>>>>for g in tbl.Fields(): print g[0]
>> 
>> ...
>> STOCKNO
>> DACC
>> DEALERACCE
>> D-ACCRTL
>> D-ACCCST
>> 
>> but I expect that one of those fancy map/lamda/list comprehension
>> functions can turn this into a list for me, but, to be honest, they
>> still make my head spin trying to figure them out.  Any ideas on how to
>> do this simply?
>
>fields = [
>     ('STOCKNO', 'C', 8, 0),
>     ('DACC', 'C', 5, 0),
>     ('DEALERACCE', 'C', 30, 0),
>     ('D-ACCRTL', 'C', 9, 0),
>     ('D-ACCCST', 'C', 9, 0)
>]
>
>
>
># The "old" way to do it would be:
>NAME_COLUMN = 0
>results = []
>for field in fields:
>     results.append(field[NAME_COLUMN])
>print results
>
>
>
>
># But list comprehensions are made for exactly this purpose
>NAME_COLUMN = 0
>results = [field[NAME_COLUMN] for field in fields]
>print results
>
Or you can take advantage of zip:

 >>> fields = [
 ...      ('STOCKNO', 'C', 8, 0),
 ...      ('DACC', 'C', 5, 0),
 ...      ('DEALERACCE', 'C', 30, 0),
 ...      ('D-ACCRTL', 'C', 9, 0),
 ...      ('D-ACCCST', 'C', 9, 0)
 ... ]
 >>> zip(*fields)[0]
 ('STOCKNO', 'DACC', 'DEALERACCE', 'D-ACCRTL', 'D-ACCCST')

Or a list of all the columns of which only the first was selected above:
 >>> zip(*fields)
 [('STOCKNO', 'DACC', 'DEALERACCE', 'D-ACCRTL', 'D-ACCCST'), ('C', 'C', 'C', 'C', 'C'), (8, 5, 30
 , 9, 9), (0, 0, 0, 0, 0)]

Since zip gives you a list of tuples, you'll have to convert if you really need a list version
of one of them:

 >>> list(zip(*fields)[0])
 ['STOCKNO', 'DACC', 'DEALERACCE', 'D-ACCRTL', 'D-ACCCST']

Regards,
Bengt Richter




More information about the Python-list mailing list