SoFunction
Updated on 2025-03-01

Detailed explanation of the method of sorting object lists according to a certain attribute by python implementation

This article describes the method of python implementing the ordering of object lists according to a certain attribute. Share it for your reference, as follows:

For an existing python list, the contents are some objects, which have some of the same attribute values. In some specific cases, you need to choose a specific sort by yourself, that is, sort by a specific attribute. I found information online. Generally speaking, there are two methods, but fundamentally, I still call itMethod to implement. Here is a simple test code snippet:

#coding:utf-8
class Person:
  def __init__(self,name,age,salary):
     = name
     = age
     = salary
obj_list = [
      Person('juneys',20,30000),
      Person('sam',20,20000),
      Person('eddy',22,25000),
      Person('eagle',25,10000)
      ]
#The first methodobj_list.sort(cmp=None, key=lambda x:, reverse=False)
print '********* First method***************************
for obj in obj_list:
  print ,
# The second method is more suitable for large amounts of data.try:
  import operator
except ImportError:
  cmpfun= lambda x:  # use a lambda if no operator module
else:
  cmpfun= ("salary") # use operator since it's faster than lambda
obj_list.sort(key=cmpfun, reverse=True)
print '************ The second method************************
for obj in obj_list:
  print ,

A Person class is constructed, and some objects are initialized and put into obj_list. Then, I want to sort them according to the salary. Method 1 and Method 2 realize ascending or descending order respectively. By analogy, sorting by age, etc. can be achieved.

The results of this example are as follows:

**********The first method************************
eagle 10000
sam 20000
eddy 25000
juneys 30000
*************The second method************************
juneys 30000
eddy 25000
sam 20000
eagle 10000

PS: Here is a demonstration tool about sorting for your reference:

Online animation demonstration insert/select/bubble/merge/hill/quick sorting algorithm process tool:
http://tools./aideddesign/paixu_ys

For more information about Python-related content, please check out the topic of this site:Introduction and Advanced Tutorial on Object-Oriented Programming in Python》、《Python data structure and algorithm tutorial》、《Summary of Python function usage tips》、《Summary of Python string operation skills》、《Summary of Python encoding operation skills"and"Python introduction and advanced classic tutorials

I hope this article will be helpful to everyone's Python programming.