python数组内排序
时间: 2023-11-04 15:06:40 浏览: 48
有多种方法可以对Python数组进行排序。以下是四种常用的方法:
方法1:使用sorted()函数进行排序
```python
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_arr = sorted(arr)
print(sorted_arr)
```
输出结果:
```
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
```
方法2:使用sort()方法进行排序
```python
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
arr.sort()
print(arr)
```
输出结果:
```
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
```
方法3:使用numpy库的sort()函数进行排序
```python
import numpy as np
arr = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])
sorted_arr = np.sort(arr)
print(sorted_arr)
```
输出结果:
```
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
```
方法4:使用heapq库的heapify()和heappop()函数进行堆排序
```python
import heapq
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
heapq.heapify(arr)
sorted_arr = []
while arr:
sorted_arr.append(heapq.heappop(arr))
print(sorted_arr)
```
输出结果:
```
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
```