当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python List sort()用法及代码示例


列出 sort() 方法

sort() 方法用于对列表元素进行升序和降序排序,该方法用这个列表(其元素要排序)调用并接受一些可选参数(在参数下面解释),该方法不返回任何值,它对这个列表进行排序。

用法:

    List_name.sort(reverse=True|False, key=function)

参数:

  • reverse=True|False– 这是一个可选参数,默认值为False,按升序对列表元素进行排序,如果设置为True,则按降序对列表元素进行排序。
  • key=function– 它也是一个可选参数,可用于指定排序条件。

返回值:

这个方法的返回类型是<class 'NoneType'>,它什么都不返回。

示例 1:不指定任何参数的排序列表

# Python List sort() Method with Example

# declaring the list
cars = ["BMW", "Porsche", "Audi", "Lexus", "Audi"]

# printing the list
print("cars before sort operation...")
print("cars:", cars)

# sorting the elements
cars.sort() # sorts in ascending order

# printing the list
print("cars after sort operation...")
print("cars:", cars)

输出

cars before sort operation...
cars: ['BMW', 'Porsche', 'Audi', 'Lexus', 'Audi']
cars after sort operation...
cars: ['Audi', 'Audi', 'BMW', 'Lexus', 'Porsche']

示例 2:指定第一个参数的排序列表

# Python List sort() Method with Example

# declaring the list
cars = ["BMW", "Porsche", "Audi", "Lexus", "Audi"]

# printing the list
print("cars before sort operation...")
print("cars:", cars)

# sorting the elements specifying reverse=True
cars.sort(reverse=True) 

# printing the list
print("cars list elements in descending order...")
print("cars:", cars)

# sorting the elements specifying reverse=False
cars.sort(reverse=False) 

# printing the list
print("cars list elements in ascending order...")
print("cars:", cars)

输出

cars before sort operation...
cars: ['BMW', 'Porsche', 'Audi', 'Lexus', 'Audi']
cars list elements in descending order...
cars: ['Porsche', 'Lexus', 'BMW', 'Audi', 'Audi']
cars list elements in ascending order...
cars: ['Audi', 'Audi', 'BMW', 'Lexus', 'Porsche']

示例 3:指定两个参数的排序列表

# Python List sort() Method with Example

# defining a function that will return length
def getLen(e):
    return len(e)
    
# declaring the list
cars = ["BMW", "Porsche", "Audi", "Lexus", "Audi"]

# printing the list
print("cars before sort operation...")
print("cars:", cars)

# sorting the elements specifying reverse=True
cars.sort(reverse=True,key=getLen) 

# printing the list
print("cars list elements in descending order based on length...")
print("cars:", cars)

# sorting the elements specifying reverse=False
cars.sort(reverse=False,key=getLen) 

# printing the list
print("cars list elements in ascending order based on length...")
print("cars:", cars)

输出

cars before sort operation...
cars: ['BMW', 'Porsche', 'Audi', 'Lexus', 'Audi']
cars list elements in descending order based on length...
cars: ['Porsche', 'Lexus', 'Audi', 'Audi', 'BMW']
cars list elements in ascending order based on length...
cars: ['BMW', 'Audi', 'Audi', 'Lexus', 'Porsche']


相关用法


注:本文由纯净天空筛选整理自 Python List sort() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。