python - 用于替换对象中键值对的 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
解决方案
您通过引用传递,关键是.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)
推荐阅读
- typescript - 在 Typescript 中通过名称获取类方法的返回类型
- amazon-web-services - “max_user_history_length”:“200”,默认 aws 个性化 - 个性化排名配方超参数是什么意思?
- amazon-web-services - ECS“为服务选择一个有效的部署组。” 代码部署
- java - 为什么 for 循环不适用于 array.size()?
- javascript - for、while 和 do while 循环之间到底有什么区别?在哪种情况下我应该使用每种情况?
- flutter - 未处理的异常:FormatException:不是有效的链接本地地址,但包含 %
- node.js - apt 命令无法找到 npm 和节点包
- angular - Devexpress Datagrid 图标图像过滤器不显示角度
- java - Windows 10 上的 TLS 1.3 密钥更新问题
- c# - 如何在 ASP.NET Core 中实现表单重置按钮?