本文主要是介绍Python 将列表中的指定位置的两个元素对调,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
https://www.runoob.com/python3/python3-list-swap-two-elements.html
定义一个列表,并将列表中的指定位置的两个元素对调。
例如,对调第一个和第三个元素:
对调前 : List = [23, 65, 19, 90], pos1 = 1, pos2 = 3
对调后 : [19, 65, 23, 90]
示例1
def swapPositions(list, pos1, pos2): list[pos1], list[pos2] = list[pos2], list[pos1] return listList = [23, 65, 19, 90]
pos1, pos2 = 1, 3print(swapPositions(List, pos1-1, pos2-1))
示例2
def swapPositions(list, pos1, pos2): first_ele = list.pop(pos1) second_ele = list.pop(pos2-1) list.insert(pos1, second_ele) list.insert(pos2, first_ele) return listList = [23, 65, 19, 90]
pos1, pos2 = 1, 3print(swapPositions(List, pos1-1, pos2-1))
示例3
def swapPositions(list, pos1, pos2): get = list[pos1], list[pos2] list[pos2], list[pos1] = get return listList = [23, 65, 19, 90] pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
这篇关于Python 将列表中的指定位置的两个元素对调的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!