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

Greg Brunet gregbrunet at NOSPAMsempersoft.com
Tue Jul 1 22:09:58 EDT 2003


"Max M" <maxm at mxm.dk> wrote in message
news:3f013fb1$0$97259$edfadb0f at dread12.news.tele.dk...
> Greg Brunet wrote:
> > 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

Max:

Thanks for that clarification of list comprehensions.  Now there's a
better "Greg comprehension" of the subject. [groan -  I know that was
bad, but it's been a rough couple of days of programming, & it usually
brings that type of comment out,  sorry ;) ]

Thanks for your help,

-- 
Greg





More information about the Python-list mailing list