gpt4 book ai didi

python - 结合两个字典,仍然保留对 python 中原始对象的引用

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:54 25 4
gpt4 key购买 nike

我有两个字典,我想将两者的内容结合起来,以便以组合的方式处理它们。我执行以下操作

a = {'one': 'fileone', 'two': 'filetow'}
b = {'three': 'filethree', 'four': 'filefour'}
clist = a.values() + b.values()

If I change anything in the clist, the change is not reflected in list a or b.

我理解的一件事是字符串是不可变类型。

我仍然希望能够引用旧字符串,并且对它们的更改必须反射(reflect)在原始字符串中。

谢谢

最佳答案

如果你用可变的东西包裹你的字符串(实际上是不可变的),你可以获得我认为你正在寻找的效果

a = {'one': ['fileone'], 'two': ['filetwo']}
b = {'three': ['filethree'], 'four': ['filefour']}

clist = a.values() + b.values()

print(clist)

a['one'][0] = 'different_file'

print(clist)

输出如下所示:

[['filetwo'], ['fileone'], ['filefour'], ['filethree']]
[['filetwo'], ['different_file'], ['filefour'], ['filethree']]

关于python - 结合两个字典,仍然保留对 python 中原始对象的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44025475/

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