Python でリストの先頭と末尾の2つの要素を入れ替える

Python3 实例 → Python3 例

リストを定義し、リストの先頭と末尾の2つの要素を入れ替えます。

例:

对调前 : [1, 2, 3]
对调后 : [3, 2, 1]

例1

def swapList(newList):
    size = len(newList)
     
    temp = newList[0]
    newList[0] = newList[size - 1]
    newList[size - 1] = temp
     
    return newList

newList = [1, 2, 3]
 
print(swapList(newList))

上記の例の出力結果は次のとおりです:

[3, 2, 1]

例2

def swapList(newList):
     
    newList[0], newList[-1] = newList[-1], newList[0]
 
    return newList
     
newList = [1, 2, 3]
print(swapList(newList))

上記の例の出力結果は次のとおりです:

[3, 2, 1]

例3

def swapList(list):
     
    get = list[-1], list[0]
     
    list[0], list[-1] = get
     
    return list
     
newList = [1, 2, 3]
print(swapList(newList))

上記の例の出力結果は次のとおりです:

[3, 2, 1]

Python3 实例 → Python3 例

其他扩展 → その他の拡張