python对数值列表排序函数
时间: 2023-11-26 09:05:51 浏览: 35
Python有多种排序函数,其中一些常用的是:
1. sorted()函数:可以对任何可迭代的对象进行排序,返回一个排好序的列表。可以指定参数key来排序自定义类型的元素。
```python
# 对数字列表排序
nums = [3, 1, 4, 1, 5, 9, 2, 6, 5]
sorted_nums = sorted(nums)
print(sorted_nums)
# 对字符串列表排序
words = ['apple', 'banana', 'cherry', 'date']
sorted_words = sorted(words)
print(sorted_words)
# 对自定义类型列表排序
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f'Person({self.name}, {self.age})'
people = [Person('Alice', 25), Person('Bob', 20), Person('Charlie', 30)]
sorted_people = sorted(people, key=lambda p: p.age)
print(sorted_people)
```
输出:
```
[1, 1, 2, 3, 4, 5, 5, 6, 9]
['apple', 'banana', 'cherry', 'date']
[Person(Bob, 20), Person(Alice, 25), Person(Charlie, 30)]
```
2. list.sort()方法:可以对一个列表进行排序,不返回任何值,直接修改原列表。可以指定参数key来排序自定义类型的元素。
```python
# 对数字列表排序
nums = [3, 1, 4, 1, 5, 9, 2, 6, 5]
nums.sort()
print(nums)
# 对字符串列表排序
words = ['apple', 'banana', 'cherry', 'date']
words.sort()
print(words)
# 对自定义类型列表排序
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f'Person({self.name}, {self.age})'
people = [Person('Alice', 25), Person('Bob', 20), Person('Charlie', 30)]
people.sort(key=lambda p: p.age)
print(people)
```
输出:
```
[1, 1, 2, 3, 4, 5, 5, 6, 9]
['apple', 'banana', 'cherry', 'date']
[Person(Bob, 20), Person(Alice, 25), Person(Charlie, 30)]
```
3. numpy.sort()函数:可以对numpy数组进行排序,返回一个排好序的数组。可以指定参数axis来沿着某个轴进行排序。
```python
import numpy as np
# 对一维数组排序
a = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5])
sorted_a = np.sort(a)
print(sorted_a)
# 对二维数组排序
b = np.array([[3, 1, 4], [1, 5, 9], [2, 6, 5]])
sorted_b = np.sort(b, axis=1)
print(sorted_b)
```
输出:
```
[1 1 2 3 4 5 5 6 9]
[[1 3 4]
[1 5 9]
[2 5 6]]
```