当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python numpy.ndarray.flat()用法及代码示例


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。