Python numpy.ndarray.flat()
numpy.ndarray.flat()函数被用作N维数组的1_D迭代器。
它不是Python内置的迭代器对象的子类,否则它就是numpy.flatiter实例。
语法 :
numpy.ndarray.flat()
参数 :
index : [tuple(int)] 迭代值的索引。
返回 :
阵列的一维迭代。
代码1:使用2D数组
# Python Program illustrating
# working of ndarray.flat()
import numpy as geek
# Working on 1D iteration of 2D array
array = geek.arange(15).reshape(3, 5)
print("2D array : \n",array )
# Using flat() : 1D iterator over range
print("\nUsing Array : ", array.flat[2:6])
# Using flat() to Print 1D represented array
print("\n1D representation of array : \n ->", array.flat[0:15])
输出 :
2D array :
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
Using Array : [2 3 4 5]
1D representation of array :
-> [ 0 1 2 ..., 12 13 14]
代码2:更改数组的值
# Python Program illustrating
# working of ndarray.flat()
import numpy as geek
# Working on 1D iteration of 2D array
array = geek.arange(15).reshape(3, 5)
print("2D array : \n",array )
# All elements set to 1
array.flat = 1
print("\nAll Values set to 1 : \n", array)
array.flat[3:6] = 8
array.flat[8:10] = 9
print("Changing values in a range : \n", array)
输出 :
2D array :
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
All Values set to 1 :
[[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]]
Changing values in a range :
[[1 1 1 8 8]
[8 1 1 9 9]
[1 1 1 1 1]]
实际上numpy.flatiter吗?
x.flat为任意数组x返回一个flatiter迭代器。它允许在n维arrays上迭代(以行为主的方式),无论是在for循环中,还是通过调用其next方法。
代码3:numpy. flattter()的角色
# Python Program illustrating
# working of ndarray.flat()
import numpy as geek
# Working on 1D iteration of 2D array
array = geek.arange(15).reshape(3, 5)
print("2D array : \n",array )
print("\nID array : \n", array.flat[0:15])
print("\nType of array,flat() : ", type(array.flat))
for i in array.flat:
print(i, end = ' ')
输出 :
2D array :
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
ID array :
[ 0 1 2 ..., 12 13 14]
Type of array,flat() :
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14