list - 当字典更改时,列表中的所有字典都会更改其值
问题描述
请帮我解决问题。
我创建一个列表。然后我附加到它的字典。在第二个字典附加后,我在列表中有 2 个相同的字典,在第三个字典附加后的列表中有 3 个相同的字典。
*** Settings ***
Library Collections
*** Variables ***
&{test_dictionary}
@{positions_list}
*** Test Cases ***
Compaund list
set to dictionary ${test_dictionary} Name=First Name Length=50 db_name=f_name
Append the dictionary to the list
set to dictionary ${test_dictionary} Name=Last Name Length=60 db_name=l_name
Append the dictionary to the list
set to dictionary ${test_dictionary} Name=Email Address Length=40 db_name=email
Append the dictionary to the list
*** Keywords ***
Append the dictionary to the list
log dictionary ${test_dictionary}
append to list ${positions_list} ${test_dictionary}
log list ${positions_list}
所以,测试后我有一个奇怪的列表:
List length is 3 and it contains following items:
0: {'Name': 'Email Address', 'Length': '40', 'db_name': 'email'}
1: {'Name': 'Email Address', 'Length': '40', 'db_name': 'email'}
2: {'Name': 'Email Address', 'Length': '40', 'db_name': 'email'}
为什么要替换第一和第二词典?
解决方案
因为在python中,一个变量(粗略地说)是一个指向内存位置的指针;字典是一个可变对象 - 例如,您可以更改该内存位置中的值。
当您将其附加到列表时,列表元素会变成“指向该内存地址的此对象” - 而不是您可能认为的“该对象的转储,作为新的内存位置”。然后你改变字典的值——例如内存地址中的值。这样做,列表成员的它也发生了变化——它仍然指向相同的内存地址,现在它拥有不同的值。
如果您希望列表中有 3 个不同的字典 - 使用 3 个变量。
或者,如果您不想这样做,请在列表中存储字典的副本 ;作为副本,如果原件这样做,它不会改变:
*** Settings ***
Library Collections
*** Variables ***
&{test_dictionary}
@{positions_list}
*** Test Cases ***
Compaund list
set to dictionary ${test_dictionary} Name=First Name Length=50 db_name=f_name
Append the dictionary to the list
set to dictionary ${test_dictionary} Name=Last Name Length=60 db_name=l_name
Append the dictionary to the list
set to dictionary ${test_dictionary} Name=Email Address Length=40 db_name=email
Append the dictionary to the list
*** Keywords ***
Append the dictionary to the list
&{dict_copy}= Copy Dictionary ${test_dictionary}
log dictionary ${dict_copy}
append to list ${positions_list} ${dict_copy}
log list ${positions_list}
推荐阅读
- r - R - 查询给定对的一对列
- python - Flask-SocketIO 无法从 redis message_queue 接收事件
- c# - 如何通过 Windows 防火墙允许 .NET Core 控制台应用程序 FTP 连接?
- visual-studio - 为什么 VS2019 会在两个地方构建我的程序集?
- css - 我是 flex 容器的新手,试图创建一个所有行都具有相同高度的网格。需要一些帮助来弄清楚我做错了什么
- ios - INActivateCarSignalIntent SiriKit 听觉/视觉意图混淆
- grails - Grails 保存一对多领域模型
- reactjs - 渲染前访问子道具
- android - 如何刷新 TextView
- sql - SQL:join:查找所有满足某些要求的对象