python - 如何设置一个变量(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)的初始值?
谢谢
解决方案
尝试使用copy.deepcopy()
:
import copy
hand2 = copy.deepcopy(hand)
正如文档所copy
解释的:
Python 中的赋值语句不复制对象,它们在目标和对象之间创建绑定。对于可变或包含可变项的集合,有时需要一个副本,以便可以更改一个副本而不更改另一个副本。
推荐阅读
- spring-webflux - 有没有办法修改 Spring 创建的默认协程上下文?
- fs - 如何使用 javascript 通过 nexe 访问已编译的 .exe 中的捆绑文件
- javascript - 从导入的 .obj 模型中拖动顶点
- r - GGPLOT 轴操作
- splunk - Splunk 查询:按 _meta 字段过滤
- tensorflow - 程序总是只预测 1 个类
- laravel - 当我转储请求时显示 Laravel Lumen .env 变量值
- sql - SQL Exec CrossTab 问题 - ',' 附近的语法不正确
- azure-resource-manager - ARM 模板 - 解释参数部分下的“参考:{}”属性
- javascript - 在反应下拉组件中创建子标题