1.创建一个Python脚本,命名为testl.py,完成以下功能。 (1)定义一个列表list1=[1,2,4,6,7,8],将其转化为数组N1。 (2)定义一个元组tupl=(1,2,3,4,5,6),将其转化为数组N2。 (3)利用内置函数,定义一个1行6列元素全为1的数组N3。 (4)将N1、N2、N3垂直连接,形成一个3行6列的二维数组N4。 (5)将N4保存为Python二进制数据文件(.npy格式。
时间: 2025-03-13 20:16:21 浏览: 59
### Python 列表、元组到 NumPy 数组的转换方法
NumPy 是一种强大的科学计算库,提供了高效的多维数组对象及其操作工具。以下是关于如何将 Python 的 `list` 和 `tuple` 转换为 NumPy 数组并保存为 `.npy` 文件的具体说明。
#### 将列表和元组转换为 NumPy 数组
可以通过 `np.array()` 函数轻松完成这一过程:
```python
import numpy as np
# 使用 list 创建 NumPy 数组
example_list = [1, 2, 3, 4]
array_from_list = np.array(example_list)
print("From List:")
print(array_from_list) # 输出: [1 2 3 4]
# 使用 tuple 创建 NumPy 数组
example_tuple = (5, 6, 7, 8)
array_from_tuple = np.array(example_tuple)
print("\nFrom Tuple:")
print(array_from_tuple) # 输出: [5 6 7 8]
```
对于不规则嵌套列表的情况,可以使用 `numpy.concatenate()` 来将其展平并转化为一维 NumPy 数组[^1]:
```python
irregular_list = [[1, 2, 3, 4], [1, 1, 0, 0], [1, 2]]
flattened_array = np.concatenate(irregular_list)
print("\nFlattened Array from Irregular List:")
print(flattened_array) # 输出: [1 2 3 4 1 1 0 0 1 2]
```
#### 数据类型的指定
在创建 NumPy 数组时,还可以通过参数 `dtype` 明确指定数据类型[^2]:
```python
int_array = np.array([1, 2, 3], dtype=np.int32)
float_array = np.array([1, 2, 3], dtype=np.float16)
print("\nInteger Array with int32 type:")
print(int_array) # 输出: [1 2 3]
print("\nFloat Array with float16 type:")
print(float_array) # 输出: [1. 2. 3.]
```
#### 高级数组创建方式
除了简单的 `np.array()` 方法外,还有其他高级函数用于生成特定模式的数组:
- **arange**: 类似于内置 range() 函数,但返回的是 NumPy 数组。
```python
ranged_array = np.arange(12).reshape(3, 4)
print("\nArray created using arange and reshaped to 3x4:")
print(ranged_array)
```
- **linspace**: 返回均匀分布的一系列数值。
```python
linspace_array = np.linspace(0, 10, num=5)
print("\nLinearly spaced array between 0 and 10 with 5 points:")
print(linspace_array)
```
#### 保存 NumPy 数组至 .npy 文件
为了长期存储或与其他程序共享 NumPy 数组,可利用 `np.save()` 函数将其保存为二进制文件格式 `.npy`:
```python
# 保存数组到名为 'saved_array.npy' 的文件中
np.save('saved_array', flattened_array)
# 加载已保存的数组
loaded_array = np.load('saved_array.npy')
print("\nLoaded Array from File:")
print(loaded_array) # 应与原始 flattened_array 完全一致
```
阅读全文
相关推荐


















