在Python中,交换列表中两个元素的位置非常简单,可以使用多重赋值进行交换,如下所示:
list = [1, 2, 3]
交换位置
list, list = list, list
print(list) 输出: [2, 1, 3]
如果你需要交换列表中任意两个不同位置上的元素,你可以指定这两个位置的索引。例如,要交换索引为`pos1`和`pos2`的元素,你可以这样做:
list = [23, 65, 19, 90]
pos1 = 1
pos2 = 3
list[pos1], list[pos2] = list[pos2], list[pos1]
print(list) 输出: [23, 90, 19, 65]
请注意,Python中的列表是可变对象,所以交换操作会直接修改原始列表