Skip to main content
 首页 » 编程设计

Python-交换函数-编程新手

2025年05月04日11haluo1

我是编程新手,正在学习 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() 

但它并没有像我需要的那样工作。它将交换 1 个索引而不是另一个。 我能得到一些帮助吗?也许解释一下我做错了什么?

请您参考如下方法:

问题是您的代码本质上等于:

myList[index1] = myList[index2] 
myList[index2] = myList[index1] 

并且为索引使用第三个“临时”变量也无济于事。带有临时变量的正确版本如下所示:

temp = myList[index1] 
myList[index1] = myList[index2] 
myList[index2] = temp 

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

myList[index1], myList[index2] = myList[index2], myList[index1]