首页 > 解决方案 > 用于替换对象中键值对的 Python 函数返回意外输出

问题描述

我写的代码:

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

标签: pythonpython-3.x

解决方案


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


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)

推荐阅读