python:交换两个数组的部分

时间:2018-10-21 23:22:44

标签: python arrays numpy

假设我在python中有两个列表:

>>> x
[0, 1, 2, 3, 4, 5]
>>> y
[0, -1, -2, -3, -4, -5]

假设我要从某个索引交换数组的元素到结尾。因此,例如,如果我让index = 3,那么我想要以下内容:

>>> x
[0, 1, 2, -3, -4, -5]
>>> y
[0, -1, -2, 3, 4, 5]

这很容易做到:

>>> tempx=x[:3]+y[3:]
>>> tempx
[0, 1, 2, -3, -4, -5]
>>> tempy=y[:3]+x[3:]
>>> tempx
[0, 1, 2, -3, -4, -5]
>>> tempy
[0, -1, -2, 3, 4, 5]
>>> x=tempx
>>> y=tempy
>>> x
[0, 1, 2, -3, -4, -5]
>>> y
[0, -1, -2, 3, 4, 5]

但是,如果x和y是numpy数组,则将无法正常工作。

>>> x=[0,1, 2, 3, 4, 5]
>>> y=[0,-1,-2,-3,-4,-5]
>>> import numpy as np
>>> x=np.array(x)
>>> y=np.array(y)
>>> x
array([0, 1, 2, 3, 4, 5])
>>> y
array([ 0, -1, -2, -3, -4, -5])
>>> tempy=y[:3]+x[3:]
>>> tempy
array([3, 3, 3])
>>> tempy=[y[:3],+x[3:]]
>>> tempy
[array([ 0, -1, -2]), array([3, 4, 5])]
>>> tempy=(y[:3],+x[3:])
>>> tempy
(array([ 0, -1, -2]), array([3, 4, 5]))

如何获得以下信息?

>>> tempx
array([0, 1, 2, -3, -4, -5])
>>> tempy
array([0, -1, -2, 3, 4, 5])

1 个答案:

答案 0 :(得分:2)

交换列表切片比您想象的要容易。

x = [1,2,3]
y = [11,22,33]

x[1:], y[1:] = y[1:], x[1:]

>>> x
[1, 22, 33]
>>> y
[11, 2, 3]

这在numpy中不起作用,因为基本切片是视图,而不是副本。如果需要,仍然可以进行显式复制。

x = np.array(range(6))
y = -np.array(range(6))

temp = x[3:].copy()
x[3:] = y[3:]
y[3:] = temp

而且,如果仔细考虑操作顺序,您仍然可以在没有显式temp变量的情况下一行完成此操作。

x[3:], y[3:] = y[3:], x[3:].copy()

无论哪种方式,我们都能得到

>>> x
array([ 0,  1,  2, -3, -4, -5])
>>> y
array([ 0, -1, -2,  3,  4,  5])
相关问题