简体   繁体   English

在列表中使用切片numpy对象

[英]Use of slicing numpy object in a list

I have a problem using the numpy slicing. 我在使用numpy切片时遇到问题。 I don't even know how to give this problem a name or title. 我什至不知道如何给这个问题起一个名字或标题。

Below are a segment of test code. 以下是一段测试代码。

import numpy
input_items = []
output_items = []
input_items.insert(0,  numpy.array([1, 2, 3], dtype=numpy.float32))
output_items.insert(0,  numpy.array([0, 0, 0], dtype=numpy.float32))
in0 = input_items[0]
out = output_items[0]

print "Before, input_items[0] : {0}".format(input_items[0])
print "Before, output_items[0]: {0}".format(output_items[0])
out[:] = in0 * 2 
#out = in0 * 2
print "After, input_item[0]  : {0}".format(input_items[0])
print "After, output_item[0] : {0}".format(output_items[0])

If I use out[:] = in0 * 2 , I will get: 如果我使用out[:] = in0 * 2 ,我将得到:

Before, input_items[0] : [ 1.  2.  3.]
Before, output_items[0]: [ 0.  0.  0.]
After, input_items[0]  : [ 1.  2.  3.]
After, output_items[0] : [ 2.  4.  6.]

If I use out = in0 * 2 , I will get: 如果使用out = in0 * 2 ,我将得到:

Before, input_items[0] : [ 1.  2.  3.]
Before, output_items[0]: [ 0.  0.  0.]
After, input_items[0]  : [ 1.  2.  3.]
After, output_items[0] : [ 0.  0.  0.]

In the code, I have assign output_items[0] to out , but obviously the use of out or out[:] can affect the result of output_items[0] . 在代码中,我已将output_items[0]分配给out ,但是显然使用outout[:]会影响output_items[0]的结果。 Could anyone figure it out? 有人能弄清楚吗?

Thanks. 谢谢。

Explanation 说明

out[:] = in0 * 2 changes your original array, because in numpy slicing is a view on the original array (which is NOT a copy) , so you get a reference to it and change it out[:] = in0 * 2更改原始数组,因为在numpy 切片中是原始数组的视图 (不是副本) ,因此您可以获取对其的引用并进行更改

out = in0 * 2 doesn't change any original array, because you are simply assigning a computed result to out (the result is stored in a fresh new separate array), therefore isn't a reference to output_items or input_items out = in0 * 2不会更改任何原始数组,因为您只是将计算结果分配给out (结果存储在新的单独数组中),因此不是对output_itemsinput_items的引用

If you need to copy an array, you can use numpy.copy() , not just assign out = output_items[0] If you assign without a copy, you are still modifying the same array, so that change will reflect elsewhere (eg between out and output_items[0] 如果您需要复制一个数组,则可以使用numpy.copy() ,而不仅仅是分配out = output_items[0]如果您没有复制就进行分配,则您仍在修改同一数组,这样更改将反映在其他地方(例如, outoutput_items[0]

So eg if you do out = output_items[0].copy() , now out has a fresh new array copied from the values in output_items[0] , but won't be affecting it 因此,例如,如果执行out = output_items[0].copy() ,则out会从output_items[0]的值复制一个新的新数组,但不会影响它

ref http://docs.scipy.org/doc/numpy/reference/generated/numpy.copy.html 参考http://docs.scipy.org/doc/numpy/reference/generated/numpy.copy.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM