array.array
时间: 2023-11-06 16:07:16 浏览: 47
array.array is a built-in Python module that provides a way to create and manipulate arrays of fixed-sized elements of the same data type.
To use the array module, you need to import it first:
```python
import array
```
Then, you can create an array by specifying the data type of its elements and the initial values:
```python
arr = array.array('i', [1, 2, 3, 4, 5])
```
In this example, we create an array of integers ('i') with the values [1, 2, 3, 4, 5].
You can access individual elements of the array using indexing:
```python
print(arr[0]) # 1
print(arr[2]) # 3
```
You can also use slicing to get a subset of the array:
```python
print(arr[1:4]) # array('i', [2, 3, 4])
```
The array module provides several methods to manipulate the array, such as append(), extend(), insert(), and remove(). Here are some examples:
```python
arr.append(6) # Add a new element to the end
arr.extend([7, 8]) # Add multiple elements to the end
arr.insert(0, 0) # Insert a new element at index 0
arr.remove(3) # Remove the first occurrence of 3
```
You can also convert an array to a list using the tolist() method:
```python
lst = arr.tolist()
```
Overall, the array module provides a more efficient way to work with arrays of fixed-size elements compared to standard Python lists.