使用Python内置函数sorted对列表进行排序
发布时间:2023-12-07 05:07:54
在Python中,可以使用内置函数sorted()对列表进行排序。sorted()函数可以接受一个可迭代的对象作为参数,并返回一个新的经过排序的列表。
以下是使用sorted()函数对列表进行排序的一些示例:
1. 对数字列表进行排序:
numbers = [9, 5, 7, 1, 3] sorted_numbers = sorted(numbers) print(sorted_numbers) # 输出:[1, 3, 5, 7, 9]
2. 对字符串列表按字母顺序进行排序:
fruits = ['apple', 'banana', 'orange', 'cherry'] sorted_fruits = sorted(fruits) print(sorted_fruits) # 输出:['apple', 'banana', 'cherry', 'orange']
3. 对包含元组的列表按照元组中的某个元素进行排序:
students = [('Tom', 22), ('John', 18), ('Jerry', 20)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students) # 输出:[('John', 18), ('Jerry', 20), ('Tom', 22)]
在第三个示例中,使用了参数key来指定排序规则,通过lambda函数定义了按元组中第二个元素来进行排序。
值得注意的是,sorted()函数返回一个新的排序后的列表,原始列表本身并没有被改变。如果需要对原列表进行排序,可以使用列表的sort()方法:
numbers = [9, 5, 7, 1, 3] numbers.sort() print(numbers) # 输出:[1, 3, 5, 7, 9]
使用sorted()函数进行排序时,还可以传递一个参数reverse=True来实现降序排列:
numbers = [9, 5, 7, 1, 3] sorted_numbers = sorted(numbers, reverse=True) print(sorted_numbers) # 输出:[9, 7, 5, 3, 1]
以上就是使用Python内置函数sorted()对列表进行排序的一些示例。sorted()函数非常灵活,可以根据需要指定不同的排序规则,包括数字和字符串的排序,以及根据元组中的某个元素进行排序等。通过灵活使用sorted()函数,可以方便地对列表进行排序操作。
