Select column from a list

Aahz aahz at pythoncraft.com
Sat Aug 29 15:33:45 EDT 2009


In article <mailman.583.1251453700.2854.python-list at python.org>,
Anthra Norell  <anthra.norell at bluewin.ch> wrote:
>Vlastimil Brom wrote:
>> 2009/8/28 hoffik <beorn at seznam.cz>:
>>>
>>> I'm quite new in Python and I have one question. I have a 2D matrix of
>>> values stored in list (3 columns, many rows). I wonder if I can select one
>>> column without having to go through the list with 'for' command.
>>
>> I guess, it won't be possible without an explicit or implicit loop;
>> you may try:
>>   
>>>>> from operator import itemgetter
>>>>> nested_list = [[1, 2, 3], [10, 20, 30], [100, 200, 300]]
>>>>> map(itemgetter(1), nested_list)
>>         
>> [2, 20, 200]
>   
>How about rotating the list with zip?
> >>> zip (*nested_list)[1]
>(2, 20, 200)

That's an implicit loop, plus it consumes an O(M*N) chunk of memory for
the intermediate list.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"I support family values -- Addams family values" --www.nancybuttons.com



More information about the Python-list mailing list