gpt4 book ai didi

list - 当字典更改时,列表中的所有字典都会更改其值

转载 作者:行者123 更新时间:2023-12-05 03:05:25 27 4
gpt4 key购买 nike

请帮我解决这个问题。

我创建了一个列表。然后我附加到它的字典。我在第二个字典附加后的列表中有 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 中,变量(粗略地说)是指向内存位置的指针;字典是一个可变对象——例如您可以更改该内存位置中的值。

当您将它追加到列表中时,列表元素会变成“指向该内存地址的这个对象”——而不是您可能认为的“该对象的转储,作为新的内存位置”。然后你改变字典的值(value) - 例如内存地址中的值。这样做,它也针对列表成员进行了更改 - 它仍然指向相同的内存地址,该地址现在拥有不同的值。

如果您希望列表中有 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}

关于list - 当字典更改时,列表中的所有字典都会更改其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51031936/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com