grouping and sorting within groups using another list

Peter Otten __peter__ at web.de
Wed Sep 2 14:38:46 EDT 2020


Peter Otten wrote:

> group_key = itemgetter(0, 3, 4)
> 
> 
> def sort_key(row, lookup={k: i for i, k in enumerate(sort_list)}):
>     return lookup[row[6]]
> 
> 
> result = list(
>     chain.from_iterable(
>         sorted(group, key=sort_key)
>         for _key, group in groupby(rows, key=group_key)
>     )
> )

It just occured to me that if the above code is what you want you can omit 
the groupby and sort with a combined key:

sorted(rows, key=lambda row: (group_key(row), sort_key(row)))

(The lambda is for illustration, you could of course merge the two key 
functions into one)



More information about the Python-list mailing list