Home  >  Article  >  Backend Development  >  How to use Python's sort(), min(), and max() functions to sort list elements?

How to use Python's sort(), min(), and max() functions to sort list elements?

PHPz
PHPzforward
2023-05-09 17:37:171610browse

The sort0 method is provided in the list object, which is used to sort the elements in the original list. After sorting, the order of the elements in the original list will change.

The syntax format is as follows:

listname.sort(key=None, reverse=False)

  • ##key: use Key to comparison

  • reverse: Optional parameter

  • False indicates ascending order

  • True Indicates descending order

  • Default ascending order

When using the sort0 method to sort a string list, the rule adopted is to sort uppercase letters first , and then sort the lowercase letters. If you want to sort a list of strings (case-insensitively), you need to specify its key parameter. Case-insensitive

char.sort(key=str.lower)

Note: The sort() function has general support for Chinese, and it is recommended to use other methods

The sorted() function does not change the original list and generates a new list after sorting

min() function gets the specified value or the minimum value in the sequence

min(a,b,c,d)min(seq)

max() function gets the specified value or The maximum value in the sequence

max(a,b,c,d)max(seq)

max() function is to take the maximum value among the multiple parameters passed in, or the maximum value among the iterable object elements passed in.

The default numeric parameter is the one with the larger value; the character parameter is the one with the lower alphabetical order. You can also pass in the named parameter key, which is a function used to specify the method of obtaining the maximum value.

default named parameter is used to specify the default value returned when the maximum value does not exist. For example, the following code:

print(max(-1,-5,key = abs))
# 先执行abs()函数再执行max()函数
print(max(1.3,'5', key=int))
# 列表和元组
# 先比较各列表低索引值的数,如果相同,再继续比较下一个索引值的数
print(max([1,2],(1,3),key=lambda x:x[1]))
array =[[1,2,3],[1,0,],[4,1,-3],[2,2,3]]
print(min(array))
print(max(array))

array =[[5,2,3],[6,9,6],[5,1,8],[5,1,7]]
print(min(array))
print(max(array))

输出结果:
-5
5
(1, 3)
[1, 0]
[4, 1, -3]
[5, 1, 7]
[6, 9, 6]

The above is the detailed content of How to use Python's sort(), min(), and max() functions to sort list elements?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete