This question already has answers here:
Changing one list unexpectedly changes another, too [duplicate]
                                
                                    (5个答案)
                                
                        
                                20天前关闭。
            
                    
我写的代码:

def function_1(object_1, list_1):
list_to_return = []
for x in list_1:
    object_1['key_1'] = [x]
    list_to_return.append(object_1)
return list_to_return

if __name__ == "__main__":
    object_main = {
        "key_1":['item1'],
        "key_2":['item1', 'item2']
    }
    list1_main = ['1','2', '3']
    ret_val = function_1(object_main, list1_main)
    print(ret_val)


编写代码以将对象中的key_1项替换为list1_main中的每个项。该功能将替换功能中预期的键。但是print语句的输出如下:

[{'key_1': ['3'], 'key_2': ['item1', 'item2']}, {'key_1': ['3'], 'key_2': ['item1', 'item2']}, {'key_1': ['3'], 'key_2': ['item1', 'item2']}]

预期输出为:

[{'key_1': ['1'], 'key_2': ['item1', 'item2']}, {'key_1': ['2'], 'key_2': ['item1', 'item2']}, {'key_1': ['3'], 'key_2': ['item1', 'item2']}]

不知道为什么代码会这样做。
的Python版本:3.8

最佳答案

您通过引用传递,关键是在字典上使用.copy。请注意,此解决方案下面返回的列表将不包含对原始字典的任何引用,但是原始字典将受到影响。如果您想保留原始字典,那么我建议您也生成一个深层副本。


def function_1(object_1:Dict, list_1):
    list_to_return = []
    for x in list_1:
        object_1['key_1'] = [x] # here u may want to manipulate a copy of ur dict instead
        list_to_return.append(object_1.copy()) # here we copy the dict

    return list_to_return

if __name__ == "__main__":
    object_main = {
        "key_1":['item1'],
        "key_2":['item1', 'item2']
    }
    list1_main = ['1','2', '3']
    ret_val = function_1(object_main, list1_main)
    print(ret_val)

关于python - Python函数替换对象中的键值对返回意外输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60062249/

10-09 12:44