Using namedtuples field names for column indices in a list of lists

Rhodri James rhodri at kynesim.co.uk
Mon Jan 9 17:28:00 EST 2017


On 09/01/17 21:40, Deborah Swanson wrote:
> Peter Otten wrote, on January 09, 2017 6:51 AM
>>
>> records = sorted(
>>     set(records),
>>     key=operator.attrgetter("Description")
>> )
>
> Good, this is confirmation that 'sorted()' is the way to go. I want a 2
> key sort, Description and Date, but I think I can figure out how to do
> that.

There's a handy trick that you can use because the sorting algorithm is 
stable.  First, sort on your secondary key.  This will leave the data in 
the wrong order, but objects with the same primary key will be in the 
right order by secondary key relative to each other.

Then sort on your primary key.  Because the sorting algorithm is stable, 
it won't disturb the relative order of objects with the same primary 
key, giving you the sort that you want!

So assuming you want your data sorted by date, and then by description 
within the same date, it's just:

records = sorted(
     sorted(
         set(records),
         key=operator.attrgetter("Description")
     ),
     key=operator.attrgetter("Date")
)

-- 
Rhodri James *-* Kynesim Ltd


More information about the Python-list mailing list