Last active
June 5, 2017 15:20
-
-
Save rupalbarman/adb96bfbd215f4504b4af911e24d39ea to your computer and use it in GitHub Desktop.
multiple attribute based sorting in python (object based and list based)
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
# sort dates using Objects, and also by lists | |
# first year wise, then month and finally day wise | |
class Date: | |
def __init__(self, d, m, y): | |
self.d = d; | |
self.m = m; | |
self.y = y; | |
def __repr__(self): | |
return '{}-{}-{}'.format(self.d, self.m, self.y) | |
def __lt__(self, d2): | |
if self.y != d2.y: | |
return self.y < d2.y | |
elif self.m != d2.m: | |
return self.m < d2.m | |
else: | |
return self.d < d2.d | |
#object based implementation | |
dates = [] | |
for _ in range(int(input())): | |
d, m, y = map(int, input().split()) | |
dates.append(Date(d, m, y)) | |
print(sorted(dates)) | |
#simple implementation | |
d= [[12, 3, 1997], [12, 3, 1992]] | |
print(sorted(d, key= lambda x: (x[2], x[1], x[0]))) #key returns tuples, which are to be considered for sorting |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment