在 NumPy 数组上设置一维迭代器


对于数组上的一个一维迭代器,请在 Python NumPy 中使用 **numpy.flat()** 方法。这是一个 numpy.flatiter 实例,其行为类似于 Python 的内置迭代器对象,但不是其子类。

NumPy 提供了全面的数学函数、随机数生成器、线性代数例程、傅里叶变换等等。它支持各种硬件和计算平台,并且可以很好地与分布式、GPU 和稀疏数组库配合使用。

步骤

首先,导入所需的库 -

import numpy as np

创建一个二维数组 -

arr = np.array([[36, 36, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69 ], [69, 80, 80, 99]])

显示我们的数组 -

print("Array...
",arr)

获取数据类型 -

print("
Array datatype...
",arr.dtype)

获取数组的维度 -

print("
Array Dimensions...
",arr.ndim)

获取数组的形状 -

print("
Our Array Shape...
",arr.shape)

获取数组的元素数量 -

print("
Elements in the Array...
",arr.size)

对于数组上的一个一维迭代器,请在 Python NumPy 中使用 numpy.flat() 方法 -

print("
Result...
",arr.flat[2]) print("
Result...
",arr.flat[7]) print("
Result...
",arr.flat[9])

获取扁平迭代器的类型 -

print("
Get the type...
",type(arr.flat))

示例

import numpy as np

# Create a 2d array
arr = np.array([[36, 36, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69], [69, 80, 80, 99]])

# Displaying our array
print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size) # For a a 1-D iterator over the array, use the numpy.flat() method in Python Numpy print("
Result...
",arr.flat[2]) print("
Result...
",arr.flat[7]) print("
Result...
",arr.flat[9]) # Get the type of the flat iterator print("
Get the type...
",type(arr.flat))

输出

Array...
[[36 36 78 88]
[92 81 98 45]
[22 67 54 69]
[69 80 80 99]]

Array datatype...
int64

Array Dimensions...
2

Our Array Shape...
(4, 4)

Elements in the Array...
16

Result...
78

Result...
45

Result...
67

Get the type...
<class 'numpy.flatiter'>

更新于: 2022年2月17日

190 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.