Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在一个数组中交换两个元素?_Python_Python 3.x_Numpy - Fatal编程技术网

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]