python中数组的用法
时间: 2024-01-04 18:46:10 浏览: 86
Python中的数组使用列表来表示。可以通过以下步骤创建和使用数组:
1. 创建数组:可使用方括号“[]”或使用内置函数“list()”来创建一个数组。
例如:
```python
arr = [1, 2, 3, 4, 5] #通过方括号创建数组
arr = list(range(1,6)) #使用list()函数创建数组
```
2. 访问数组元素:可以使用索引值来访问数组元素。索引值从0开始,最后一个元素的索引值为数组长度减一。
例如:
```python
arr = [1, 2, 3, 4, 5]
print(arr[0]) #输出1
print(arr[4]) #输出5
```
3. 修改数组元素:可以使用索引值来修改数组元素。
例如:
```python
arr = [1, 2, 3, 4, 5]
arr[0] = 6 #将第一个元素修改为6
print(arr) #输出[6, 2, 3, 4, 5]
```
4. 遍历数组:可以使用for循环遍历数组中的所有元素。
例如:
```python
arr = [1, 2, 3, 4, 5]
for i in arr:
print(i) #依次输出1, 2, 3, 4, 5
```
5. 数组长度:可以使用内置函数“len()”来获取数组的长度。
例如:
```python
arr = [1, 2, 3, 4, 5]
print(len(arr)) #输出5
```
6. 数组切片:可以使用切片操作获取数组的子集。
例如:
```python
arr = [1, 2, 3, 4, 5]
print(arr[1:4]) #输出[2, 3, 4]
```
7. 数组排序:可以使用内置函数“sorted()”或“sort()”方法对数组进行排序。
例如:
```python
arr = [3, 1, 4, 2, 5]
sorted_arr = sorted(arr) #使用sorted()函数排序
print(sorted_arr) #输出[1, 2, 3, 4, 5]
arr.sort() #使用sort()方法排序
print(arr) #输出[1, 2, 3, 4, 5]
```
以上就是Python中数组的基本用法。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)