2015-10-27 25 views
0

所以,我有一個這樣的功能:爲什麼函數結束時列表的值會發生變化?

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 

爲什麼列表expenses_list失去了它的價值,當函數Undo_Action結束。我的意思是,當我在標籤1上打印費用表時,將執行修改,但是當函數退出時,修改不會保留在標籤2上,所以我有一個不同的列表。

回答

3

這是因爲現在expenses_listUndo_Action指的是另一個列表中你做expenses_list=deepcopy(expenses_lists_que[current_position-1])後。

您需要做的是將該行更改爲expenses_list[:]=deepcopy(expenses_lists_que[current_position-1])。在這種情況下,將會修改expenses_list而不是引用另一個列表。

正因爲如此,如果你寫expenses_list = [1,2]裏面的功能,也不會影響功能外expenses_list,因爲現在expenses_list指的是另一個對象(名單)。但是,如果您寫入expenses_list[:] = [1,2]expenses_list[0], expenses_list[1] = 1, 2,您的外部expenses_list將被更改。

相關問題