Python Array Element Swap: Quick Guide
In Python, you can swap two elements in an array using the following method:
def swap_elements(arr, idx1, idx2):
arr[idx1], arr[idx2] = arr[idx2], arr[idx1]
# 示例
arr = [1, 2, 3, 4, 5]
swap_elements(arr, 0, 2)
print(arr) # [3, 2, 1, 4, 5]
Here is a swap_elements function defined, which takes an array arr and two indexes idx1 and idx2 as parameters, then swaps the values of the elements at indexes idx1 and idx2.