程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python detailed analysis of sorted sorting function with actual combat code (all)

編輯:Python

Catalog

  • Preface
  • 1. Basic functions
  • 2. Parameters on
    • 2.1 reverse Parameters
    • 2.2 cmp Parameters
    • 2.3 key Parameters
  • 3. Practical analysis
    • 3.1 Date sort
    • 3.2 python web

Preface

Analyze a function alone , Or the algorithm needs , Or it is needed by the project ( I am the second )
, The demand is for redis Sort the storage in the database , The latest list is displayed in the form and placed at the top ( Logical thinking will also be mentioned in the following project practice ), Let's first look at how functions and extensions are used

1. Basic functions

sorted function ( Other programming languages are similar )
stay python in , Sort the list in ascending or descending order , You can also sort according to your own custom rules

python Different versions of function prototypes are different , Not compatible , See the version

python2 The function prototype of is as follows :

sorted(iterable, cmp=None, key=None, reverse=False)

The parameters are as follows :(cmp、key Are values taken from objects )

  • iterable: Objects that can be iterated ( See the following supplementary explanation )
  • cmp: Comparison function , greatly 1, Xiao Wei -1, Is equal to 0( Similar to the comparison function of programming language )
  • key: Specify the value in the iteration object , Sort this value
  • reverse: Specify the sort order , The default is ascending (False), Descending (True)

Add : Iteratable objects can generally be regarded as containers that store many elements , Traverse it to get the element , Common iteratable object types are python There's a list of 、 Yuan Zu 、 Dictionaries 、 aggregate , See my previous article analysis for details :python Detailed analysis of data types ( The attached code )

python3 Function prototype of :

sort(*, key=None, reverse=None)

Parameters like python2, It's just removed cmp Comparison , But the official also gave instructions ( Compatibility ), See the following for specific usage

2. Parameters on

2.1 reverse Parameters

Use reverse In ascending or descending order :

list = ['m', 'a', 'n', 'o', 'n', 'g']
# Descending 
list.sort(reverse=True)
print( list )

2.2 cmp Parameters

Use cmp Function to compare , If you don't write reverse It's in ascending order (False)
python2 The use of :

list= [1, 3, 2, 4]
list.sort(cmp=lambda a, b: a - b)
print(list) # [1, 2, 3, 4]

stay python3 Writing like this will make mistakes
The following problems occurred :

Traceback (most recent call last):
File "script.py", line 2, in <module>
nums.sort(cmp=lambda a, b: a - b)
TypeError: 'cmp' is an invalid keyword argument for sort()
Exited with error status 1

because python3 We have already put this cmp The function of is removed
If you want to use python3 Of cmp( Check the official website document to introduce from functools import cmp_to_key), The specific use is as follows :

from functools import cmp_to_key
nums = [1, 3, 2, 4]
nums.sort(key=cmp_to_key(lambda a, b: a - b))
print(nums) # [1, 2, 3, 4]

2.3 key Parameters

Sort by specifying the key position

list = [(2, 2), (3, 4), (4, 1), (1, 3)]
# Call function 
list.sort(key=xx)
def xx(elem):
return elem[1]
print(list) # Output [(4, 1), (2, 2), (1, 3), (3, 4)]

Refine into lambda The expression is as follows :

list = [(2, 2), (3, 4), (4, 1), (1, 3)]
# Specify the second element sort , Use lambda expression 
list.sort(key=lambda list:list[1])
print(list) # Output [(4, 1), (2, 2), (1, 3), (3, 4)]

3. Practical analysis

3.1 Date sort

Sort the time and date
Want to convert its date uniformly , adopt sorted Sort

import datetime
def get_timestamp(date):
return datetime.datetime.strptime(date,"%Y-%m-%d %H:%M:%S").timestamp()
s1=['2022-07-11 11:00:00', '2022-07-12 12:00:00', '2022-07-13 13:00:00']
s=sorted(s1,key=lambda date: get_timestamp(date))
print s

3.2 python web

stay python web in
In itself redis The database has stored the field value of the last modification time ( Join yourself )
Get the field values in the form and sort them accordingly ( It was originally a dictionary , First convert to a list )
adopt sorted Sort

def get_all_time_appid_names():
projects = list(Project.objects())
sorted(projects, key=lambda project: project.last_modify_time)
result = []
for project in projects:
appid = project.appid
if appid or appid is 0:
result.append((appid, project.gamename))
return result

Specifically Project Is the field value defined in the form


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved