python implements a method for sorting object lists by an attribute
- 2021-06-28 12:58:14
- OfStack
An example of how python implements sorting an object list by an attribute.Share it for your reference, as follows:
For an existing python list, the content is a few objects, these objects have some same attribute values, in some specific cases, you need to choose a specific sort, that is, sort according to a specific attribute, find the following information on the Internet, generally there are two methods, but fundamentally, it is still called
list.sort
Method implementation.Here is a simple test code snippet:
#coding:utf-8
class Person:
def __init__(self,name,age,salary):
self.name = name
self.age = age
self.salary = salary
obj_list = [
Person('juneys',20,30000),
Person('sam',20,20000),
Person('eddy',22,25000),
Person('eagle',25,10000)
]
# No. 1 Method
obj_list.sort(cmp=None, key=lambda x:x.salary, reverse=False)
print '*********** No. 1 Method ***********************'
for obj in obj_list:
print obj.name,obj.salary
# No. 2 Method , Better for large amounts of data .
try:
import operator
except ImportError:
cmpfun= lambda x: x.count # use a lambda if no operator module
else:
cmpfun= operator.attrgetter("salary") # use operator since it's faster than lambda
obj_list.sort(key=cmpfun, reverse=True)
print '*********** No. 2 Method ***********************'
for obj in obj_list:
print obj.name,obj.salary
Construct an Person class, then initialize some objects into obj_list, and then want to sort by wage, method 1 and method 2 achieve ascending or descending order respectively.Age ranking can also be achieved by this analogy.
The results of this example are as follows:
***********Method 1***********************
eagle 10000
sam 20000
eddy 25000
juneys 30000
***********Method 2*********************
juneys 30000
eddy 25000
sam 20000
eagle 10000
PS: Here is another presentation tool about sorting for your reference:
Online animation demonstrates the Insert/Select/Bubble/Merge/Hill/Quick Sort algorithm process tool:
http://tools.ofstack.com/aideddesign/paixu_ys
More readers interested in Python-related content can view this site's topics: Introduction and Advanced Python Object-Oriented Programming, Python Data Structure and Algorithms, Python Function Usage Skills Summary, Python String Operation Skills Summary, Python Coding Operation Skills Summary, and Python Introduction and Advanced Classic Tutorials.
I hope that the description in this paper will be helpful to everyone's Python program design.