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
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 )
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
Use reverse In ascending or descending order :
list = ['m', 'a', 'n', 'o', 'n', 'g']
# Descending
list.sort(reverse=True)
print( list )
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]
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)]
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
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
adopt vs You can export dynami
One 、 introduction How to bec