This question is based on previous Stackoverflow answer. The problem seems too big for me.
I now have sorting function sort_multi(lst, index_normal, index_reversed)
which takes input list, and two parameters which indicates which column is sorted in normal order and which in reverse:
from pprint import pprint
from itertools import groupby, chain
l = ((1, 'b'),
(1, 'd'),
(2, 'a'),
(1, 'a'))
def sort_multi(lst, index_normal, index_reversed):
return list(chain.from_iterable([sorted(list(j), key=lambda v:v[index_reversed], reverse=True) for i, j in groupby(sorted(lst), key=lambda v:v[index_normal])]))
pprint(sort_multi(l, 0, 1), width=10) # index 0 is sorted normally, 1 in reversed order.
Output:
[(1, 'd'),
(1, 'b'),
(1, 'a'),
(2, 'a')]
What I want is extend the function to work for any number of indices. Eg.
For example input of 3 columns:
l = ((1, 'c', 'aa'),
(2, 'b', 'bb'),
(1, 'c', 'cc'),
(1, 'd', 'dd'))
sort_multi(l, reversed=(False, True, True))
Gives output:
[(1, 'd', 'dd'),
(1, 'c', 'cc'),
(1, 'c', 'aa'),
(2, 'b', 'bb')]
The tuples can contains strings, integers, ...