在函数中修改字典而不使用返回语句

2024-04-19 01:28:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试修改函数中的字典。因为字典是可变的数据类型。我想知道是否需要一份回执?你知道吗

例如:

def modify_dict(a_dict,a_key,a_value):
    a_dict = {a_key:a_value}

# Why wouldn't the function actually modify the dictionary? 
# Wouldn't the dictionary still be changed to sample_dict={e_key:e_value} anyways?

sample_dict = {b_key:b_value,c_key:c_value,d_key:d_value}
modify_dict(sample_dict,e_key,e_value)

Tags: thesamplekey函数dictionary字典valuedef
3条回答

当您在函数内重新分配a_dict时,实际上是在创建一个新字典,它与函数作用域外的字典同名。如果您更新字典,更改将在函数范围之外可见,但您正在重新分配名称。你知道吗

您的modify dict没有修改变量。它正在重新绑定它。你知道吗

尝试:

def modify_dict(a_dict,a_key,a_value):
    a_dict[a_key] = a_value

而且没有。。你不需要“返回”。你知道吗

Python对象变量是引用
python中的赋值运算符不处理值本身,而是处理那些引用。你知道吗

a = [1,2] # creates object [1,2]
b = [3,4] # creates object [3,4]

# a now holds a reference to [1,2]
# b now holds a reference to [3,4]

c = a

# c now holds a reference to [1,2] as well

c = [5,6] # creates object [5,6]

# c now holds a reference to [5,6] and forgets about the [1,2].
# This does NOT change the [1,2] object.

这同样适用于函数调用:

def modify_dict(a_dict,a_key,a_value):
    # a_dict is a REFERENCE to whatever the argument of the function is

    a_dict = {a_key:a_value} # creates a new dict
    # a_dict now holds a reference to that NEW dict and forgets what it
    # was previously referencing.
    # This does not influence the object that was given as an argument

我认为这里要理解的关键概念是,函数中的参数是对对象的引用,而不是对象本身。你知道吗

要真正更改命令,您需要直接访问它而不是分配给它,例如:

def modify_dict(a_dict,a_key,a_value):
    a_dict[a_key] = a_value

相关问题 更多 >