Python 將列表中的指定位置的兩個元素對調

Document 對象參考手冊 Python3 實例

定義一個列表,並將列表中的指定位置的兩個元素對調。

例如,對調第一個和第三個元素:

對調前 : 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 list
 
List = [23, 65, 19, 90]
pos1, pos2  = 1, 3
 
print(swapPositions(List, pos1-1, pos2-1))

以上實例輸出結果為:

[19, 65, 23, 90]

實例 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 list
 
List = [23, 65, 19, 90]
pos1, pos2  = 1, 3
 
print(swapPositions(List, pos1-1, pos2-1))

以上實例輸出結果為:

[19, 65, 23, 90]

實例 3

def swapPositions(list, pos1, pos2):
 
    get = list[pos1], list[pos2]
       
    list[pos2], list[pos1] = get
       
    return list
 
List = [23, 65, 19, 90]
 
pos1, pos2  = 1, 3
print(swapPositions(List, pos1-1, pos2-1))

以上實例輸出結果為:

[19, 65, 23, 90]

Document 對象參考手冊 Python3 實例