Tag:python element return
student_tuples = [(' John ', ' A ', 15), (' Jane ', ' B ', 12), (' Dave ', ' B ', 10 )]print "1:", Sorted (Student_tuples, key=itemgetter (2)) ## Sort by third element print "2:", Sorted (student_tuples, key=itemgetter) ## first press the second element, such as the same, and then sort by the third element print "3:", Sorted ( Student_tuples, key=itemgetter (2), reverse=true) ## in reverse order of the third element class student: def __init__ (self, name, grade, age): self.name = name self.grade = grade self.age = age def __repr__ (self): return repr ((self.name, Self.grade, self.age) student_objects = [student (' John ', ' A ', 15), student (' Jane ', ' B ', 12), Student (' Dave ',   ' B ', 10)]print "4:", Sorted (Student_objects, key=attrgetter (' age ')) ## by class student () Inside the Age sort print "5:", Sorted (student_objects, key=lambda student: student.age) ## Ibid. print "6:", Sorted (student_tuples, key=lambda student: student[2)) ## effect Ibid. The difference is the above example with attributes, this with subscript print "7:", Sorted (Student_objects, key=attrgetter (' Grade ', ' age ')) ## First Sort by class student (), such as the same, in the class student () within the age of print "8:", Sorted (Student_objects, key=attrgetter (' Age '), reverse=true ## by Class student () The ## is sorted by age first and then by grade s=sorted (student_objects,key= Attrgetter (' age ')) print "9:", Sorted (S,key=attrgetter (' Grade '), reverse=true) ## Sort by first element, if the first element is the same, Keep previous sequencing data = [(' Red ', 1), (' Blue ', 1), (' Red ', 2), (' Blue ', 2) ]print "Ten:", Sorted (data, key=itemgetter (0)) ## results ## 1: [(' Dave ', ' B ', 10), (' Jane ', ' B ', &NBsp;12), (' John ', ' a ', 15)]## 2: [(' John ', ' a ', 15), (' Dave ', ' B ',  10), (' Jane ', ' B ', 12)]## 3: [(' John ', ' A ', 15), (' Jane ', ') B ', 12), (' Dave ', ' B ', 10)]## 4: [(' Dave ', ' B ', 10), (' Jane ', ' B ', 12), (' John ', ' A ', 15)]## 5: [(' Dave ', ' B ', 10), (' Jane ', ' B ', 12), (' John ', ' A ', 15)]## 6: [(' Dave ', ' B ', 10), (' Jane ', ' B ', 12), (' John ', ' a ', 15)]## 7: [(' John ', ' a ', , (' Dave ', ' B ', 10), (' Jane ', ' B ', 12)]## 8: [(' John ', ' A ', 15), (' Jane ', ' B ', 12), (' Dave ', ' B ', 10)]## 9: [(' Dave ', ') B ', 10), (' Jane ', ' B ', 12), (' John ', ' A ', 15)]## 10: [(' Blue ', 1), (' Blue ', 2), (' Red ', 1), (' Red ', 2)]
This article is from the "ohgenlong16300blog.com" blog, make sure to keep this source http://ohgenlong16300.blog.51cto.com/499130/1689733
Python Sort Induction