Python 内置函数 sorted() 和 sort() 的区别是什么?
发布时间:2023-05-28 19:16:31
Python 内置函数 sorted() 和 sort() 都是用来对列表进行排序的。然而,两者之间有几个重要的区别:
1. sorted() 函数返回一个排好序的新列表,而 sort() 会改变原来的列表,并且不返回任何结果。
示例:
numbers = [3, 1, 4, 1, 5, 9, 2, 6] sorted_numbers = sorted(numbers) print(numbers) # [3, 1, 4, 1, 5, 9, 2, 6] print(sorted_numbers) # [1, 1, 2, 3, 4, 5, 6, 9] numbers.sort() print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
2. sorted() 函数接受任何可迭代对象,而 sort() 只能用于列表。
示例:
numbers_tuple = (3, 1, 4, 1, 5, 9, 2, 6) sorted_tuples = sorted(numbers_tuple) print(sorted_tuples) # [1, 1, 2, 3, 4, 5, 6, 9] numbers_tuple.sort() # 报错 TypeError: 'tuple' object has no attribute 'sort'
3. sorted() 函数可以接受额外的关键字参数来指定排序顺序,而 sort() 只能按照默认顺序排序。
示例:
words = ['banana', 'apple', 'pear', 'orange'] sorted_words = sorted(words, key=len) print(sorted_words) # ['pear', 'apple', 'orange', 'banana'] words.sort(key=len) print(words) # ['pear', 'apple', 'orange', 'banana']
4. sorted() 函数可以对任何类型的对象排序,只要定义了比较函数,而 sort() 只能对列表中的元素进行排序。
示例:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f'Person(name={self.name}, age={self.age})'
people = [Person('Alice', 25), Person('Bob', 18), Person('Charlie', 32)]
sorted_people = sorted(people, key=lambda p: p.age)
print(sorted_people) # [Person(name=Bob, age=18), Person(name=Alice, age=25), Person(name=Charlie, age=32)]
# 报错 AttributeError: 'list' object has no attribute 'age'
people.sort(key=lambda p: p.age)
5. sorted() 函数具有稳定性,即对于同时具有相等关键字的元素,原始顺序会得到保留。而 sort() 函数没有稳定性,相等元素的相对顺序是随机的。
示例:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5] sorted_numbers = sorted(numbers) print(sorted_numbers) # [1, 1, 2, 3, 4, 5, 5, 6, 9] numbers.sort() print(numbers) # [1, 1, 2, 3, 4, 5, 5, 6, 9]
在使用 sorted() 和 sort() 函数时,需要根据具体场景和需求选择。如果需要对原列表进行排序,sort() 可能会更快,但是如果想保留原列表的不变性,sorted() 更为安全。如果需要自定义排序标准,则必须使用 sorted() 函数。
