如何在一个数组中交换两个元素?

时间:2019-08-22 08:01:15

标签: python python-3.x numpy

我有一个像这样的数组:

a=np.array([2,7])

a=[2,7]

我想交换相同的数组,例如7,2,该怎么做?

答案应类似于7,2

a=[7,2]

2 个答案:

答案 0 :(得分:2)

尝试np.flip(a,0)有关更多信息,请参见this

答案 1 :(得分:2)

#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))
相关问题