numpy.ndarray.flat():N-dimensional數組上的1_D迭代器。
它不是Python的內置迭代器對象的子類,否則不是numpy.flatiter實例。
參數:
index : [tuple(int)] index of the values to iterate
返回:
1-D iteration of array
代碼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 repersented 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,flatiter迭代器均由x.flat返回。它允許在for-loop中或通過調用其next方法在N-dimensional數組上進行迭代(以行為主)。
代碼3:numpy.flatitter()的角色
# 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
參考文獻:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flat.html#numpy.ndarray.flat
相關用法
注:本文由純淨天空篩選整理自 numpy.ndarray.flat() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。