sort和reversed
时间: 2023-07-05 08:32:31 浏览: 52
sort和reversed也是Python中常用的内置函数。sort函数用于原地排序一个可迭代对象(如列表),它会修改原对象,而不是返回一个新的对象。默认情况下,sort函数根据元素的大小进行升序排序,但可以通过传递关键字参数key来指定排序规则。例如:
```python
numbers = [3, 1, 4, 2, 5]
numbers.sort()
print(numbers) # 输出 [1, 2, 3, 4, 5]
words = ["apple", "banana", "cherry", "date"]
words.sort(key=len)
print(words) # 输出 ["date", "apple", "banana", "cherry"]
```
reversed函数用于反转一个可迭代对象(如列表),返回一个新的迭代器对象。例如:
```python
numbers = [1, 2, 3, 4, 5]
reversed_numbers = reversed(numbers)
print(list(reversed_numbers)) # 输出 [5, 4, 3, 2, 1]
words = ["apple", "banana", "cherry", "date"]
reversed_words = reversed(words)
print(list(reversed_words)) # 输出 ["date", "cherry", "banana", "apple"]
```
需要注意的是,reversed函数返回的是迭代器对象,如果需要,可以通过list函数将迭代器对象转换为列表对象。