【问题标题】:Python function to replace key value pair in object returns unexpected output [duplicate]替换对象中键值对的Python函数返回意外输出[重复]
【发布时间】:2020-05-20 13:37:58
【问题描述】:

我写的代码:

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

【问题讨论】:

  • 您将相同的对象/引用附加到list_to_return。无论在何处引用,都会看到原始列表的更改
  • 你通过引用传递,传递一个副本
  • 谢谢。有效。 list_to_return.append(object_1) 我把这一行改成 list_to_return.append(dict(object_1))

标签: python python-3.x


【解决方案1】:

你是通过引用传递的,关键是在字典上使用.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)

【讨论】:

    【解决方案2】:

    您每次都将相同的字典附加到list_to_return。因为字典是可变的。您应该每次都复制它。此外,您正在更改给定的 dict,您也应该复制它:

    def function_1(object_1, list_1):
        object_1 = object_1.copy()
        list_to_return = []
        for x in list_1:
            object_1['key_1'] = [x]
            list_to_return.append(object_1.copy())
        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)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 2019-10-25
      • 1970-01-01
      • 2018-01-24
      • 2021-11-07
      相关资源
      最近更新 更多