[Python-ideas] Multiple level sorting in python where the order of some levels may or may not be reversed
Chris Angelico
rosuav at gmail.com
Sun Oct 16 00:46:25 EDT 2016
More information about the Python-ideas mailing list
Sun Oct 16 00:46:25 EDT 2016
- Previous message (by thread): [Python-ideas] Multiple level sorting in python where the order of some levels may or may not be reversed
- Next message (by thread): [Python-ideas] Multiple level sorting in python where the order of some levels may or may not be reversed
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Sun, Oct 16, 2016 at 3:29 PM, Alireza Rafiei <alireza.rafiei94 at gmail.com> wrote: > What I ended up doing is: > >> count_list = sorted(count_list, >> key=lambda x: (x[1], map(lambda x: -x, map(ord, >> x[0]))), >> reverse=True) > > > which works. Now my solution is very specific to structures like [(str, > int)] where all strs are lower case and besides ord makes it to be both > limited in use and also more difficult to add extra levels of sorting. Interesting. Personally, I would invert this; if you're sorting by an integer and a string, negate the integer, and keep the string as-is. If that doesn't work, a custom class might help. # untested class Record: reverse = False, True, True, False, True def __init__(data): self.data = data def __lt__(self, other): for v1, v2, rev in zip(self.data, other.data, self.reverse): if v1 < v2: return rev if v2 > v1: return not rev return False This is broadly similar to how tuple.__lt__ works, allowing you to flip the logic of whichever ones you like. ChrisA
- Previous message (by thread): [Python-ideas] Multiple level sorting in python where the order of some levels may or may not be reversed
- Next message (by thread): [Python-ideas] Multiple level sorting in python where the order of some levels may or may not be reversed
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-ideas mailing list