Python-Swap函数 - 编程新手

J.R*_*ley 1 python

我是编程新手,我正在学习Python.我必须创建一个将在列表中交换2个索引的函数.给出列表但是要交换的索引需要由用户输入.到目前为止,我已经能够想出这个......

def listSwap():
    print("This program will swap two indices within a list")
    myList = [3, 4, 2, 5, 1, 14, 23, 1]
    print("Here is your list... ", myList)
    index1 = eval(input("Pick an index from the list you would like to swap... "))
    index2 = eval(input("Now pick another index to swap with the first... "))

    tempIndex = index1
    myList[index1] = myList[index2]
    myList[index2] = myList[tempIndex]
    print("Here is your new list with swapped indices", myList)


def main():
    listSwap()

main()
Run Code Online (Sandbox Code Playgroud)

但它不像我需要它那样工作.它会交换1个索引但不会交换另一个索引.我可以得到一些帮助吗?也许解释一下我做错了什么?

ber*_*eal 7

问题是你的代码基本上等于:

myList[index1] = myList[index2]
myList[index2] = myList[index1]
Run Code Online (Sandbox Code Playgroud)

并且索引的第三个"临时"变量的使用没有帮助.带有temp变量的正确版本如下所示:

temp = myList[index1]
myList[index1] = myList[index2]
myList[index2] = temp
Run Code Online (Sandbox Code Playgroud)

但是,幸运的是,Python有更优雅的交换价值方式:

myList[index1], myList[index2] = myList[index2], myList[index1] 
Run Code Online (Sandbox Code Playgroud)