Python 如何在一个数组中交换两个元素?
我有这样一个数组:Python 如何在一个数组中交换两个元素?,python,python-3.x,numpy,Python,Python 3.x,Numpy,我有这样一个数组: a=np.array([2,7]) a=[2,7] 我想交换相同的数组,比如7,2,还有什么要做的吗 答案应该是7,2 a=[7,2] 请尝试np.flip(a,0)有关更多信息,请参阅 #a=np.array([2,7]) a=[2,7] # Reversing a list using slice notation print (a[::-1]) # [7, 2] # The reversed() method print (list(reversed(a))
a=np.array([2,7])
a=[2,7]
我想交换相同的数组,比如7,2,还有什么要做的吗
答案应该是7,2
a=[7,2]
请尝试np.flip(a,0)
有关更多信息,请参阅
#a=np.array([2,7])
a=[2,7]
# Reversing a list using slice notation
print (a[::-1]) # [7, 2]
# The reversed() method
print (list(reversed(a))) # [7, 2]
交换列表中的两个元素:
# Swap function
def swapPositions(list, pos1, pos2):
list[pos1], list[pos2] = list[pos2], list[pos1]
return list
a=[2,7]
pos1, pos2 = 0, 1
print(swapPositions(a, pos1 - 1, pos2 - 1))
a[0],a[1]=a[1],a[0]