[英]swapping 2 terms in a numpy array, python
import numpy as np
old_order=np.array([0,1,2,3,4,5,6,7,8])
new_order=old_order
swap_1,swap_2=random.sample(range(0,9),2)
new_order[swap_1],new_order[swap_2]=old_order[swap_2],old_order[swap_1]
print(old_order,new_order)
So I am trying to swap two random element within an array.所以我试图在一个数组中交换两个随机元素。 old_order would be the original array and new_order would be the array after the switch happened.
old_order 将是原始数组,new_order 将是切换发生后的数组。 What I don't understand is that why would the values of the old_order be changed
我不明白的是为什么 old_order 的值会被改变
enter image description here在此处输入图像描述
I have narrow down the problem to我已将问题缩小到
new_order[swap_1],new_order[swap_2]=old_order[swap_2],old_order[swap_1]
If this line is remove, both new order and old order will be the same.如果删除此行,则新订单和旧订单都将相同。
There is only one array.只有一个数组。
old_order
and new_order
are both bound to the same array. old_order
和new_order
都绑定到同一个数组。 This line这条线
new_array = old_array
makes a new reference.做一个新的参考。 It doesn't make a copy of the data.
它不会复制数据。 If you really need a copy, use
old_order.copy()
.如果您真的需要副本,请使用
old_order.copy()
。
new_order=old_order.copy()
Create a new array for new_order.为 new_order 创建一个新数组。 Otherwise new_order, old_order take the same memory.
否则new_order、old_order取相同的memory。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.