What is the need of ellipsis[…] while modifying array values in numpy?

回眸只為那壹抹淺笑 提交于 2019-12-13 19:43:19

问题


import numpy as np                
a = np.arange(0,60,5)            
a = a.reshape(3,4)                                    

for x in np.nditer(a, op_flags = ['readwrite']):          
   x[...] = 2*x              
print 'Modified array is:'              
print a

In the above code, why can't we simply write x=2*x instead of x[...]=2*x?


回答1:


No matter what kind of object we were iterating over or how that object was implemented, it would be almost impossible for x = 2*x to do anything useful to that object. x = 2*x is an assignment to the variable x; even if the previous contents of the x variable were obtained by iterating over some object, a new assignment to x would not affect the object we're iterating over.

In this specific case, iterating over a NumPy array with np.nditer(a, op_flags = ['readwrite']), each iteration of the loop sets x to a zero-dimensional array that's a writeable view of a cell of a. x[...] = 2*x writes to the contents of the zero-dimensional array, rather than rebinding the x variable. Since the array is a view of a cell of a, this assignment writes to the corresponding cell of a.

This is very similar to the difference between l = [] and l[:] = [] with ordinary lists, where l[:] = [] will clear an existing list and l = [] will replace the list with a new, empty list without modifying the original. Lists don't support views or zero-dimensional lists, though.



来源:https://stackoverflow.com/questions/52135891/what-is-the-need-of-ellipsis-while-modifying-array-values-in-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!