在修改numpy数组中使用省略号 [英] use of ellipsis in modifying numpy arrays

查看:579
本文介绍了在修改numpy数组中使用省略号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此处看到了以下代码,该代码试图迭代一个numpy数组arr并修改其元素.但是,我不太了解此处使用省略号(...)的目的.如果我删除了省略号(即使用x = x * 2),则不会修改arr的元素.希望从您那里得到一些提示!谢谢.

I saw the following code here, which tries to iterate a numpy array arr and modify its elements. However, I do not quite understand what the purpose of using ellipsis (...) is here. If I removed the ellipsis (i.e. using x = x*2), then the elements of arr will not be modified. Hope to get some hints from you! Thanks.

for x in np.nditer(arr,op_flags='readwrite'):
    x[...] = x*2;

推荐答案

省略号...是内置的Python符号,用于在N维Numpy数组中指定切片,例如a[0,...,0]等效于a[0,:,:,:,0]用于5维数组a.

Ellipsis ... is a built-in Python symbol that is used to specify slices in N-dimensional Numpy arrays, such as a[0,...,0] is equivalent to a[0,:,:,:,0] for a 5-D array a.

nditer对象使用此语法使迭代器可写.

The nditer objects use this syntax to make iterators writable.

使用迭代器对象作为左值会修改该对象本身,而不是其所引用的数组中的位置.因此,x[...]是用于取消引用迭代器的语法.

Using an iterator object as an lvalue modifies the object itself instead of the location in an array it is referring to. So x[...] is the syntax that is used for dereferencing an iterator.

您还可以使用此语法访问要读取的值,但这是多余的.

You could also use this syntax to access the value for reading, but this is redundant.

还请注意,您的op_flags语法不正确.它应该是列表或元组.

Also note that your syntax for op_flags is incorrect. It should be a list or a tuple.

for x in np.nditer(arr,op_flags=['readwrite']):
    x[...] = x*2;

这篇关于在修改numpy数组中使用省略号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆