Python:交换两个数组的部分内容

2024-03-29 10:43:03 发布

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

假设python中有两个列表:

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

假设我想从某个索引交换数组的元素,直到最后。例如,如果我让索引=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])

Tags: importnumpy信息元素列表asnp数组
1条回答
网友
1楼 · 发布于 2024-03-29 10:43:03

交换列表片段比你想象的要容易。你知道吗

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

相关问题 更多 >