Python 为什么函数结束时列表的值会发生变化?
所以,我有一个函数:Python 为什么函数结束时列表的值会发生变化?,python,Python,所以,我有一个函数: def Undo_Action(expenses_list ,expenses_lists_que,current_position): ''' Undo the last performed action Input:expenses_list - The current list of expenses expenses_lists_que - The list containing the instances of last
def Undo_Action(expenses_list ,expenses_lists_que,current_position):
'''
Undo the last performed action
Input:expenses_list - The current list of expenses
expenses_lists_que - The list containing the instances of last lists
current_possition- The posion in the que where our current expenses_list is
'''
if len(expenses_lists_que)>0:
expenses_list=deepcopy(expenses_lists_que[current_position-1])
current_position=current_position-1
else:
print("You din not performed any actions yet!")
print ("Label 1:" ,expenses_list)
return current_position
我在这个函数中调用它
def Execute_Main_Menu_Action( expenses_list, action, expenses_lists_que,current_position):
'''
Executes a selected option from the main menu
Input: The expenses list on which the action will be performed
The action which should be exectued
Output: The expenses list with the modifications performed
'''
if action == 1 :
Add_Expense(expenses_list)
elif action== 5:
Show_Expenses_List(expenses_list)
elif action== 2:
Remove_Expense_Menu( expenses_list)
elif action== 3:
Edit_Expense_Menu(expenses_list)
elif action==4:
Obtain_Data_Menu (expenses_list)
elif action==6:
current_position=Undo_Action(expenses_list ,expenses_lists_que,current_position)
print("Label 2:" , expenses_list)
return current_position
为什么在函数Undo_操作结束时列表会失去其值。我的意思是,当我在标签1上打印费用列表时,会执行修改,但当函数退出时,修改不会保留在标签2上,因此我有一个不同的列表。这是因为现在
撤销操作中的费用列表在执行费用列表=deepcopy之后引用了另一个列表(费用清单[当前职位-1])
您需要做的是将该行更改为expenses\u list[:]=deepcopy(expenses\u list\u que[current\u position-1])
。在这种情况下,expenses\u list
将被修改到位,而不是引用另一个列表
因此,如果在函数内部编写费用清单=[1,2]
,则不会影响函数外部的费用清单
,因为函数中的费用清单
现在引用的是另一个对象(列表)。但是,如果编写费用清单[:]=[1,2]
,或费用清单[0],费用清单[1]=1,2
,您的外部费用清单
将被更改。这是因为现在撤消操作中的费用清单
在执行费用清单=deepcopy(费用清单[当前位置-1])
之后引用了另一个清单
您需要做的是将该行更改为expenses\u list[:]=deepcopy(expenses\u list\u que[current\u position-1])
。在这种情况下,expenses\u list
将被修改到位,而不是引用另一个列表
因此,如果在函数内部编写费用清单=[1,2]
,则不会影响函数外部的费用清单
,因为函数中的费用清单
现在引用的是另一个对象(列表)。但是,如果编写费用清单[:]=[1,2]
,或费用清单[0],费用清单[1]=1,2
,您的外部费用清单
将被更改。这是因为现在撤消操作中的费用清单
在执行费用清单=deepcopy(费用清单[当前位置-1])
之后引用了另一个清单
您需要做的是将该行更改为expenses\u list[:]=deepcopy(expenses\u list\u que[current\u position-1])
。在这种情况下,expenses\u list
将被修改到位,而不是引用另一个列表
因此,如果在函数内部编写费用清单=[1,2]
,则不会影响函数外部的费用清单
,因为函数中的费用清单
现在引用的是另一个对象(列表)。但是,如果编写费用清单[:]=[1,2]
,或费用清单[0],费用清单[1]=1,2
,您的外部费用清单
将被更改。这是因为现在撤消操作中的费用清单
在执行费用清单=deepcopy(费用清单[当前位置-1])
之后引用了另一个清单
您需要做的是将该行更改为expenses\u list[:]=deepcopy(expenses\u list\u que[current\u position-1])
。在这种情况下,expenses\u list
将被修改到位,而不是引用另一个列表
因此,如果在函数内部编写费用清单=[1,2]
,则不会影响函数外部的费用清单
,因为函数中的费用清单
现在引用的是另一个对象(列表)。但是,如果编写费用清单[:]=[1,2]
,或费用清单[0],费用清单[1]=1,2,您的外部费用列表将被更改