在循环中更新numpy数组

2024-04-19 18:45:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我从下面得到了一些奇怪的结果,但对python比较陌生,所以可能会弄乱一些东西。以下内容:

import numpy as np

a = np.array([1,2,3,4])
print(a)

old_a = a

for x in range(0,1):
   new_a = old_a
   new_a[0] = old_a[1]
   new_a[1] = old_a[2]
   new_a[2] = old_a[3]
   new_a[3] = old_a[0]
   print(new_a)

[1 2 3 4]
[2 3 4 2]

我本以为第二个数组是[2 3 4 1]。在

但是,如果我用下面的“clean”def创建一个新数组,它似乎可以工作

^{pr2}$

我缺少什么?我如何避免干净的def?在

谢谢

****更新以下问题****

谢谢你的回复。所以,尽管下面有关于滚动函数的响应,这是实现与滚动函数相同的最佳方法吗?在

import numpy as np

a = np.array([1,2,3,4])
print(a)

old_a = a

for x in range(0,10):
   new_a = old_a.copy()
   new_a[0] = old_a[1]
   new_a[1] = old_a[2]
   new_a[2] = old_a[3]
   new_a[3] = old_a[0]
   old_a = new_a.copy()
   print(new_a)

再次感谢

编辑

这就是我决定的:

import numpy as np

a = np.array([1,2,3,4])
print(a)

old_a = a
new_a = np.zeros_like(old_a)

for x in range(0,10):
    new_a[0] = old_a[1]
    new_a[1] = old_a[2]
    new_a[2] = old_a[3]
    new_a[3] = old_a[0]
    old_a = new_a.copy()
    print(new_a)

[1 2 3 4]
[2 3 4 1]
[3 4 1 2]
[4 1 2 3]
[1 2 3 4]
[2 3 4 1]
[3 4 1 2]
[4 1 2 3]
[1 2 3 4]
[2 3 4 1]
[3 4 1 2]

谢谢大家!在


Tags: 函数inimportnumpynewfordefas
3条回答

看看这是否有助于你理解你在做什么:

import numpy as np

a = np.array([1,2,3,4])
print(a)

old_a = a

for x in range(0,1):
    new_a = old_a
    new_a[0] = old_a[1]
    print  new_a
    new_a[1] = old_a[2]
    print  new_a
    new_a[2] = old_a[3]
    print  new_a
    new_a[3] = old_a[0]
    print(new_a)

[1 2 3 4]
[2 2 3 4]
[2 3 3 4]
[2 3 4 4]
[2 3 4 2]

所以当你这样做时,new_a[3] = old_a[0],位置{}已经是“2”。 下面是你所期望的。在

^{pr2}$

最快的方法是“花式”索引:

a     = np.array([1,2,3,4])
new_a = a[np.array([1,2,3,0])]
print new_a

array([2, 3, 4, 1])

即使这个答案不能回答您的问题,但对于您的具体情况,如果您正在寻找的是将元素移动一个的话,还有一个更简单的解决方案。它避免了你陷入困境的复杂性,并且简化了事情。在

import numpy as np

a = np.array([1,2,3,4])
b = np.roll(a, -1)
print(a, b)

输出

^{pr2}$

当您更改new_a的值时,您也在更改old_a的值,因为您通过指定new_a = old_a来执行浅拷贝而不是深层复制:

new_a[0] = old_a[1]
new_a[1] = old_a[2]
new_a[2] = old_a[3]
#old_a[0] is already old_a[1], as you reassigned it on line #1
new_a[3] = old_a[0] 

下面是浅拷贝和深拷贝的区别,如Python Docs

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

对于numpy数组,可以使用deepcopy或{}来避免clean def:

^{pr2}$

编辑

更新后的问题后,看起来您想更新old_a本身,因此无需将其copy更新为新数组,您只需按以下方式实现您要做的事情:

import numpy as np
a = np.array([1,2,3,4])
print(a)
old_a = a
for x in range(0,1):
   old_a[0], old_a[1], old_a[2], old_a[3] = old_a[1], old_a[2], old_a[3], old_a[0]
   print(old_a)

相关问题 更多 >