Python交换函数编程新手
我是编程新手,正在学习Python。我必须做一个函数,在一个列表中交换两个索引。列表已给出,但要交换的索引需要由用户输入。到目前为止,我已经能够想出这个Python交换函数编程新手,python,Python,我是编程新手,正在学习Python。我必须做一个函数,在一个列表中交换两个索引。列表已给出,但要交换的索引需要由用户输入。到目前为止,我已经能够想出这个 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 =
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]
问题在于,您的代码本质上等于:
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]
首先,不要使用
eval
相反,请使用:
index1=int(输入(“从要交换的列表中选择索引…”)
index2=int(输入(“现在选择另一个索引与第一个交换…”)
其次,不需要临时保存索引值,只需保存具有该索引的列表项:
index\u value\u 1=MyList[index1]
然后执行切换
myList[index1] = myList[index2]
myList[index2] = index_value_1
首先,不要使用
eval
相反,请使用:
index1=int(输入(“从要交换的列表中选择索引…”)
index2=int(输入(“现在选择另一个索引与第一个交换…”)
其次,不需要临时保存索引值,只需保存具有该索引的列表项:
index\u value\u 1=MyList[index1]
然后执行切换
myList[index1] = myList[index2]
myList[index2] = index_value_1
def您的_交换(_列表,A,B):
断言A>0和A0和B
定义您的交换(交换列表A、B):
断言A>0和A0和B
这里不是交换“索引”,而是交换存储在数组中的值,使用索引取消引用。
给出一个列表:
a = [1, 2, 5, 3]
print(a[0])
打印“1”。当您这样做时:
a[0] = a[1]
将a[0]
处的值替换为a[1]
处的值,从而丢失a[0]
处的值。现在您将拥有a=[2,2,5,3]
您试图实现的是在位置0
和1
处交换数字。为此,您需要在a[0]
处复制一个值,以便在使用a[1]
重写时不会丢失它
这样做:
a = [1, 2, 5, 3]
index1 = 0
index2 = 1
temp = a[index1] # stores "1" in temp
a[index1] = a[index2] # changes a to [2, 2, 5, 3] by replacing a[0] with value in a[1]
a[index2] = temp # stores "1" inside temp into a[1], changing a to [2, 1, 5, 3]
这是一个常见的问题,与。这里不是交换“索引”,而是交换存储在数组中的值,使用索引取消引用。
给出一个列表:
a = [1, 2, 5, 3]
print(a[0])
打印“1”。当您这样做时:
a[0] = a[1]
将a[0]
处的值替换为a[1]
处的值,从而丢失a[0]
处的值。现在您将拥有a=[2,2,5,3]
您试图实现的是在位置0
和1
处交换数字。为此,您需要在a[0]
处复制一个值,以便在使用a[1]
重写时不会丢失它
这样做:
a = [1, 2, 5, 3]
index1 = 0
index2 = 1
temp = a[index1] # stores "1" in temp
a[index1] = a[index2] # changes a to [2, 2, 5, 3] by replacing a[0] with value in a[1]
a[index2] = temp # stores "1" inside temp into a[1], changing a to [2, 1, 5, 3]
这是一个常见问题,与相关。非常感谢!我不敢相信这是一个如此容易的解决办法。。但我现在明白我做错了什么。再次感谢!非常感谢你!我不敢相信这是一个如此容易的解决办法。。但我现在明白我做错了什么。再次感谢!