我在一个数组中有2个列表。我想切换列表顺序。列表2变为列表1,列表1变为列表2。我将为您提供一些有关如何有效切换这些列表的帮助。谢谢
我在python中有以下代码。
RestoredData_Array = np.dot(featuresT.reshape(2,2), FinalData1_Matrix.reshape(2,20))
RestoredData_Array
实际结果:
array([
[ 2.3065 , 9.21202097, 2.03334271, 8.12104732,
1.02492108, 4.09347257, -0.54700703, -2.18471288,
0.15896622, 0.63490144, -0.51904295, -2.07302602,
-2.11190708, -8.43482867, -3.33826623, -13.33283264,
-3.24268925, -12.95110399, -3.39616989, -13.56409637],
[ -9.93383348, -39.6751278 , -11.51169937, -45.9770284 ,
-13.27291919, -53.01123343, -12.73236969, -50.85231155,
-13.35424863, -53.33605825, -14.86736232, -59.37934246,
-17.41605181, -69.55865355, -17.84717309, -71.28052577,
-19.07951685, -76.20243193, -20.72810021, -82.78677378]])
所需结果:
array([
[ -9.93383348, -39.6751278 , -11.51169937, -45.9770284 ,
-13.27291919, -53.01123343, -12.73236969, -50.85231155,
-13.35424863, -53.33605825, -14.86736232, -59.37934246,
-17.41605181, -69.55865355, -17.84717309, -71.28052577,
-19.07951685, -76.20243193, -20.72810021, -82.78677378]
[ 2.3065 , 9.21202097, 2.03334271, 8.12104732,
1.02492108, 4.09347257, -0.54700703, -2.18471288,
0.15896622, 0.63490144, -0.51904295, -2.07302602,
-2.11190708, -8.43482867, -3.33826623, -13.33283264,
-3.24268925, -12.95110399, -3.39616989, -13.56409637]])
看起来您想要的就是将[a, b]
更改为[b, a]
,其中a
和b
是您的列表。
有很多方法。下面的代码是最短的,可用于列表和numpy数组。
Reversed_Array = RestoredData_Array[::-1]
这是切片技巧。请参阅here以了解其工作原理。
交换两个数组的值:
a=[1]
b=[2]
a,b = b,a
print(a)
print(b)
交换嵌套数组的值:
c=[[1],[2]] # here c[0] have value [1] & c[1] have value [2]
c[0],c[1] = c[1],c[0] # here we are interchanging the value of c[0] & c[1]
print(c)
这些示例可以帮助您转换数组
对于您的代码,这可能有效:
RestoredData_Array = np.dot(featuresT.reshape(2,2), FinalData1_Matrix.reshape(2,20))
RestoredData_Array[0],RestoredData_Array[1] = RestoredData_Array[1],RestoredData_Array[0]
print(RestoredData_Array)