Python sort函数
作者:野牛程序员:2023-08-08 18:22:57python阅读 2738
在 Python 中,sort()
是列表(List)对象的一个方法,用于对列表进行排序。这个方法会直接修改原列表,而不会创建一个新的排序后的列表。
sort()
方法可以接受一些参数来自定义排序方式,但通常情况下,它会根据元素的默认比较规则进行排序。
以下是使用 sort()
方法进行列表排序的示例:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] numbers.sort() print(numbers) # 输出:[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
如果想要按照降序排序,你可以使用 reverse
参数:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] numbers.sort(reverse=True) print(numbers) # 输出:[9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
需要注意的是,sort()
方法是针对列表的,对于其他数据类型(如字符串),可以使用内置函数 sorted()
来进行排序,sorted()
不会修改原始数据,而是返回一个新的排序后的对象。
word = "hello" sorted_word = sorted(word) print(sorted_word) # 输出:['e', 'h', 'l', 'l', 'o']
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:python中return一定执行吗
- 下一篇:c++元素的个数叫做数组的?