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

Max M maxm at mxm.dk
Tue Jul 1 04:03:11 EDT 2003


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


regards Max M





More information about the Python-list mailing list