python list 排序
在Python中,对列表进行排序可以使用内置的sort()方法,或者使用内置函数sorted()。sort()方法会就地修改列表,而sorted()函数会返回一个新的排序后的列表,原列表不变。
以下是使用sort()和sorted()方法的示例代码:
使用sort()方法
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
my_list.sort() # 就地排序
print(my_list) # 输出: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
使用sorted()函数
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_list = sorted(my_list) # 返回新的排序列表
print(sorted_list) # 输出: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
如果需要对包含字典的列表进行排序,可以通过指定排序的键:
对包含字典的列表进行排序
my_list = [{‘name’: ‘Alice’, ‘age’: 25},
{‘name’: ‘Bob’, ‘age’: 22},
{‘name’: ‘Charlie’, ‘age’: 30}]
按照年龄升序排序
my_list.sort(key=lambda x: x[‘age’])
print(my_list)
输出: [{‘name’: ‘Bob’, ‘age’: 22}, {‘name’: ‘Alice’, ‘age’: 25}, {‘name’: ‘Charlie’, ‘age’: 30}]
sort()和sorted()方法都可以接受额外的参数,如reverse=True来进行降序排序。