Python基础知识:整理15 列表的sort方法

1 sorted() 方法

之前我们学习过 sorted() 方法,可以对列表、元组、集合及字典进行排序                                                                                     

# 1.列表
ls = [1, 10, 8, 4, 5]
ls_new = sorted(ls, reverse=True)
print(ls_new)   # [10, 8, 5, 4, 1]
print("----------------------")

# 2.元组
tp = (1, 10, 8, 4, 5)
tp_new = sorted(tp, reverse=True)
print(tp_new)   # [10, 8, 5, 4, 1]
print("----------------------")

# 3.集合
st = {1, 10, 8, 4, 5}
st_new = sorted(st, reverse=True)
print(st_new)   # [10, 8, 5, 4, 1]
print("----------------------")

# 4.字典
dic = {'a': 1, 'b': 10, 'c': 8, 'd': 4, 'e': 5}
dic_new = sorted(dic, reverse=True)
print(dic_new)   # ['e', 'd', 'c', 'b', 'a']
print("----------------------")

Python基础知识:整理15 列表的sort方法_第1张图片

但是上述的方法对于嵌套的数据就不好实现排序了,sort()方法便可以登场了!

2 sort() 方法

要求:如下嵌套列表,要求对外层列表进行排序,排序的依据是内层列表的第二个元素数字,之前的sorted方法已经不适用了

Python基础知识:整理15 列表的sort方法_第2张图片

2.1 带名函数形式

# 1. 带名函数形式
my_list = [["a",33], ["b",55], ["c",21], ["d",100], ["e",5]]


def takeSecond(elem):
    return elem[1]

my_list.sort(key=takeSecond, reverse=True)
print(my_list)

Python基础知识:整理15 列表的sort方法_第3张图片

2.2 lambda匿名函数形式

my_list = [["a",33], ["b",55], ["c",21], ["d",100], ["e",5]]
my_list.sort(key=lambda x: x[1], reverse=True)
print(my_list)

Python基础知识:整理15 列表的sort方法_第4张图片

你可能感兴趣的:(Python,python)