生成numpy.ndarray
时间: 2023-09-01 13:11:12 浏览: 90
生成numpy.ndarray的方法有多种。可以使用列表、元组或其他可迭代对象来创建一个numpy数组。下面是几个例子:
1. 使用列表创建一个一维数组:
```python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
# 输出:[1 2 3 4 5]
```
2. 使用元组创建一个一维数组:
```python
import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)
# 输出:[1 2 3 4 5]
```
3. 使用ndarray函数创建一个一维数组:
```python
import numpy as np
arr = np.ndarray(shape=(5,), buffer=np.array([1, 2, 3, 4, 5]))
print(arr)
# 输出:[1. 2. 3. 4. 5.]
```
4. 使用列表嵌套创建一个二维数组:
```python
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
# 输出:
# [[1 2 3]
# [4 5 6]]
```
5. 使用ndarray函数创建一个二维数组:
```python
import numpy as np
arr = np.ndarray(shape=(2, 3), buffer=np.array([[1, 2, 3], [4, 5, 6]]))
print(arr)
# 输出:
# [[1. 2. 3.]
# [4. 5. 6.]]
```
总结来说,生成numpy.ndarray的方法包括使用列表、元组、ndarray函数等。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [Python NumPy 创建数组(ndarray)](https://blog.csdn.net/weixin_64338372/article/details/128659329)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文