首页 > 解决方案 > 如何设置一个变量(1)等于另一个变量(2),当变量(2)在Python中发生时不会改变?

问题描述

我对python还是比较陌生,所以尽量不要因为任何误解而把我钉在十字架上。当将变量hand 发送到另一个更新并返回它的函数时,我无法复制变量hand 的初始值。当我希望变量(hand2 )成为变量(手)的初始值时,我将变量(手)的返回值作为复制变量(手2)的值

def play_game(word_list):
   word_list = load_words
   while True:
      answer = input('\nEnter \'n\' for a new random hand, \'r\' to play the last hand, or \'e\' to exit the game: ')
      if answer == 'n':
         hand = deal_hand(HAND_SIZE)   #Here i get a randomly generated hand
         hand2 = hand    #I want to save the randomly generated hand before it's updated
         play_hand(hand,word_list)   #This function updates the hand
      elif answer == 'r':
         play_hand(hand2,word_list)  #I want to play the un-updated hand but i get the updated hand instead

有什么办法可以让variable(hand2)等于variable(hand)的初始值?

谢谢

标签: pythonvariables

解决方案


尝试使用copy.deepcopy()

import copy
hand2 = copy.deepcopy(hand)

正如文档所copy解释的:

Python 中的赋值语句不复制对象,它们在目标和对象之间创建绑定。对于可变或包含可变项的集合,有时需要一个副本,以便可以更改一个副本而不更改另一个副本。


推荐阅读