gpt4 book ai didi

Python-交换函数-编程新手

转载 作者:太空宇宙 更新时间:2023-11-04 07:18:07 25 4
gpt4 key购买 nike

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

关于Python-交换函数-编程新手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32518196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com