Python 通过引用和字典副本传递

Python Pass by Reference and dictionary copies

我正在 Python 中编写脚本来模拟辩论赛。但是我 运行 遇到了这个看起来像引用传递问题的奇怪错误,但有一些行为不应受到引用传递的影响。

基本上,团队是一个团队字典,其中每个团队都有一堆字段,包括胜负字段,当我第一次建立团队时,它们都被初始化为 0。

然后 df.apda_tournament() 接受球队字典,并根据模拟对其进行修改以给出球队的输赢,以及 returns 更新后的球队字典。

由于引用传递的工作原理,传递给 df.apda_tournament() 的团队字典和返回的字典最终都被改变了,因为该函数改变了传递字典中记录的得失和 returns 它。因此:

apda_results == apda_teams

Returns如我所料。

奇怪的是 df.apda_tournament() 还更改了原始团队字典,apda_teams 是其副本。所以它最终是:

apda_teams == teams

也returns正确。这很奇怪,因为看起来 apda_teams 当我声明它只是对团队的引用而不是副本时,我不会期望这是因为我在函数之外声明它。

有人能准确解释一下这是怎么回事吗?另外,我怎样才能避免这种情况 apda_teams 实际上是团队字典的唯一副本,而不仅仅是对内存中记录的引用?

下面附上代码:

import debate_functions as df

dbtr_num = 64
team_num = dbtr_num / 2
dbtr_mn_mn = 200
dbtr_mn_std = 80
dbtr_std_mn = 80
dbtr_std_std = 60
judge_bias = 70

dbtrs = df.make_debaters(dbtr_num, dbtr_mn_mn, dbtr_mn_std, dbtr_std_mn, dbtr_std_std)
teams = df.make_teams(dbtrs, dbtr_mn_mn, dbtr_mn_std)
print(teams)
apda_teams = teams
para_teams = teams

apda_results = df.apda_tournament(5, apda_teams, judge_bias)
print('Check this')
print(apda_results == apda_teams)
print(apda_teams == teams)

运行它returns:

Check this
True
True

在python列表中,字典是可变的(我们可以修改内容)。因此,无论何时将列表、字典传递给任何函数或分配给任何变量,它都会指向给定变量的引用。

字符串、数字、元组是不可变的(我们不能修改内容)。因此,无论何时将元组、数字串入任何函数或分配给任何变量,它都会复制值。