在Python中交换列表的值

问题描述 投票:0回答:1

假设我有一个数组 nums 并想像这样交换两个数字

nums[i], nums[nums[i]-1] = nums[i], nums[nums[i]-1]

为什么这不起作用?我理解这是因为 nums[i] 被用作第二个变量的引用。如果有人能解释为什么会失败,我将不胜感激

python python-3.x list
1个回答
0
投票

你可以这样做(如果我正确理解你的问题)来交换列表中2个值的位置:

list = ["val1", "val2", "val3", "val4", "val5"] # here is the list


# code to swap 2nd and 4th element:
swapvalue1 = list[1] # stores value in second position
swapvalue2 = list[3] # stores value in fourth position

del list[1] # removes the value in the second position
list.insert(1, swapvalue2) # places the fourth value in the second position

del list[3] # removes the value in the fourth position
list.insert(3, swapvalue1) # places the original second value in the fourth position
© www.soinside.com 2019 - 2024. All rights reserved.