Using namedtuples field names for column indices in a list of lists
Peter Otten
__peter__ at web.de
Mon Jan 9 18:27:20 EST 2017
Rhodri James wrote:
> 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")
> )
While stable sort is nice in this case you can just say
key=operator.attrgetter("Description", "Date")
Personally I'd only use sorted() once and then switch to the sort() method.
More information about the Python-list
mailing list