假设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])
交换列表片段比你想象的要容易。你知道吗
这在numpy中不起作用,因为基本切片是视图,而不是副本。如果你想的话,你仍然可以做一个明确的拷贝。你知道吗
而且,如果仔细考虑操作顺序,仍然可以在一行中完成,而无需显式的temp变量。你知道吗
不管怎样,我们都可以
相关问题 更多 >
编程相关推荐