Created
September 9, 2022 13:49
-
-
Save faniska/9c9148595b97935c4979c4693f7d0e5d to your computer and use it in GitHub Desktop.
Sort python list containing tuples with dict
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
class CustomCompare(object): | |
def __init__(self, obj, order): | |
self.obj = obj | |
self.order = order | |
def __lt__(self, other): | |
return self._index_of(self.obj) < self._index_of(other.obj) | |
def __gt__(self, other): | |
return self._index_of(self.obj) > self._index_of(other.obj) | |
def __eq__(self, other): | |
return self._index_of(self.obj) == self._index_of(other.obj) | |
def __le__(self, other): | |
return self._index_of(self.obj) <= self._index_of(other.obj) | |
def __ge__(self, other): | |
return self._index_of(self.obj) >= self._index_of(other.obj) | |
def __ne__(self, other): | |
return self._index_of(self.obj) != self._index_of(other.obj) | |
def _index_of(self, obj): | |
name = obj[2]['name'] | |
if name in self.order: | |
return self.order.index(name) | |
else: | |
return len(self.order) | |
a = [ | |
(0, 3, {'name': 'C'}), | |
(0, 2, {'name': 'B'}), | |
(0, 1, {'name': 'A'}), | |
(0, 4, {'name': 'D'}), | |
] | |
x = sorted(a, key=lambda l: CustomCompare(l, order=['A', 'C', 'B', 'D'])) | |
print(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment