Python sorted function, pythonsorted Function
I learned about socket programming two days ago and was disgusted when I asked a great God a question. There is a feeling that I want to run without learning to go. The great God said that I should do some small exercises like Operating Files and serial numbers to deepen my understanding. The following is a small exercise he gave me:
1. datas = [['sherry', 19, 'female '], ['flora', 21, 'female '], ['june', 15, 'femal'], which is sorted by the first letter and age;
2. Compare the output results based on the given output mode and supplement the Person class;
class_mates = {'sherry':[18,'male'],'june':[20,'female'],'flora':[19,'female'],'alina':[21,'male']}class Person(object): def __init__(self,name,age): self.name = namep1 = Person('sherry',20)p2 = Person('june',20)if p1<p2:print('p1:{} less than p2:{}'.format([p1.name,p1.age],[p2.name,p2.age]))else:print('p1:{} gte than p2:{}'.format([p1.name,p1.age],[p2.name,p2.age]))
In this simple way, I spent an afternoon (face hitting)
def get_first(info): first_value = info[0][0] return first_value na = sorted(datas,key=get_first) print(na) def age_sort(info): return info[1] print(sorted(datas,key=age_sort))
Question 1
class_mates = {'sherry':[18,'male'],'june':[20,'female'],'flora':[19,'female'],'alina':[21,'male']}class Person(object): def __init__(self,name,age): self.name = name self.age = age def __lt__(self,others): if(self.age<others.age): return 1 elif(self.age==others.age): if(self.name[0]<others.name[0]): return 1 else: return 0 return 0p1 = Person('sherry',20)p2 = Person('june',20)if p1<p2: print('p1:{} less than p2:{}'.format([p1.name,p1.age],[p2.name,p2.age]))else: print('p1:{} gte than p2:{}'.format([p1.name,p1.age],[p2.name,p2.age]))
Question 2 answer
View the python official documentation and summarize the get knowledge.
1、sorted
(Iterable [, key] [, reverse])
Returns a reordered list with two optional keyword parameters (the parameter name is used instead of the position to specify the parameter ).
KeyDefines a function with parameters, extracts an element of the list as the parameter of this function, and returns the value as your keyword. The default value is None (directly compare the elements of the list)
ReverseIs a Boolean value. True indicates reverse sorting of elements in the list.
2. ln (a, B): When a <B is used, the _ ln _ (a, B) function is automatically called, therefore, we need to redefine the _ ln (a, B) _ function in the class to define when to return true and when to return false. Each type has its own ln () function, so it can also be called when being redefined.