class MyObj(object):
def __init__(self, start, last):
self.start = start
self.last = last
def __str__(self):
return (self.start, self.last)
def __repr__(self):
return "{}-{}".format(self.start, self.last)
# sort #### object list #####
objList = [MyObj(9,1), MyObj(1,9),MyObj(4,2), MyObj(2,4)]
# sort it by last
sortedObjList = sorted(objList, key=lambda x: x.last)
print(str(sortedObjList))
# sort it by first
def compareFirst(x):
return x.start
sortedObjList = sorted(objList, key=compareFirst)
print(str(sortedObjList))
--
class MyObj(object):
def __init__(self, start, last):
self.start = start
self.last = last
def __str__(self):
return (self.start, self.last)
def __repr__(self):
return "{}-{}".format(self.start, self.last)
def __eq__(self, other):
return self.last == other.last
def __lt__(self, o):
return self.last < o.last
print("########2")
# sort #### object list #### with self defined compare func
objList = [MyObj(9, 1), MyObj(1, 9), MyObj(4, 2), MyObj(2, 4)]
# sort it
sortedObjList = sorted(objList)
print(str(sortedObjList))
--
print("########3")
# sort #### tuple list ####
tupleList = [(2,9), (6,3), (3,7)]
# sort it by int at index 1
sortedTupleList = sorted(tupleList, key=lambda x:x[1])
print(sortedTupleList)
# sort it by int at index 0
sortedTupleList = sorted(tupleList, key=lambda x:x[0])
print(sortedTupleList)
# #### sort dict ####
data = {1:'b', 2:'a'}
# get values ordered by values
res = sorted(data.values())
print(res)
# get keys ordered by values
res = sorted(data.keys(), key=data.get)
print(res)
# get a list of tuples ordered by values
res = sorted(data.items(), key=lambda x:x[1])
print(res)
--
References:
http://home.wlu.edu/~lambertk/pythontojava/DefCompare.htm
网友评论