我是编程新手,我正在学习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个索引但不会交换另一个索引.我可以得到一些帮助吗?也许解释一下我做错了什么?
python ×1