简体   繁体   中英

Use of slicing numpy object in a list

I have a problem using the numpy slicing. 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:

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:

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] . 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 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

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]

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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