Python程序交换列表中的两个元素
在Python中给定一个列表并提供元素的位置,编写一个程序来交换列表中的两个元素。
例子:
Input : List = [23, 65, 19, 90], pos1 = 1, pos2 = 3
Output : [19, 65, 23, 90]
Input : List = [1, 2, 3, 4, 5], pos1 = 2, pos2 = 5
Output : [1, 5, 3, 4, 2]
方法#1:简单交换,使用逗号赋值
由于元素的位置是已知的,我们可以简单地交换元素的位置。
Python3
# Python3 program to swap elements
# at given positions
# Swap function
def swapPositions(list, pos1, pos2):
list[pos1], list[pos2] = list[pos2], list[pos1]
return list
# Driver function
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
Python3
# Python3 program to swap elements
# at given positions
# Swap function
def swapPositions(list, pos1, pos2):
# popping both the elements from list
first_ele = list.pop(pos1)
second_ele = list.pop(pos2-1)
# inserting in each others positions
list.insert(pos1, second_ele)
list.insert(pos2, first_ele)
return list
# Driver function
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
Python3
# Python3 program to swap elements at
# given positions
# Swap function
def swapPositions(list, pos1, pos2):
# Storing the two elements
# as a pair in a tuple variable get
get = list[pos1], list[pos2]
# unpacking those elements
list[pos2], list[pos1] = get
return list
# Driver Code
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
输出:
[19, 65, 23, 90]
方法 #2:使用内置 list.pop()函数
在pos1弹出元素并将其存储在变量中。同样,在pos2处弹出元素并将其存储在另一个变量中。现在将两个弹出的元素插入到彼此的原始位置。
Python3
# Python3 program to swap elements
# at given positions
# Swap function
def swapPositions(list, pos1, pos2):
# popping both the elements from list
first_ele = list.pop(pos1)
second_ele = list.pop(pos2-1)
# inserting in each others positions
list.insert(pos1, second_ele)
list.insert(pos2, first_ele)
return list
# Driver function
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
输出:
[19, 65, 23, 90]
方法#3:使用元组变量
将pos1和pos2的元素作为一对存储在元组变量中,比如get 。解压缩该列表中具有pos2和pos1位置的元素。现在,该列表中的两个位置都被交换了。
Python3
# Python3 program to swap elements at
# given positions
# Swap function
def swapPositions(list, pos1, pos2):
# Storing the two elements
# as a pair in a tuple variable get
get = list[pos1], list[pos2]
# unpacking those elements
list[pos2], list[pos1] = get
return list
# Driver Code
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
输出:
[19, 65, 23, 90]