在Python中向列表中添加字典,但数据重复。

huangapple go评论76阅读模式
英文:

Add dictionary in List in Python but, data is duplicated

问题

data = []
dic = dict.fromkeys(['a', 'b', 'c'], 0)

value = 1
for i in range(3):
    key = list(dic.keys())
    for j in range(len(dic)):
        dic[key[j]] = value
        value += 1
    data.append(dic)

for i in data:
    print(i)

在这段代码中,我期望的结果是这样的:

{'a': 1, 'b': 2, 'c': 3}
{'a': 4, 'b': 5, 'c': 6}
{'a': 7, 'b': 8, 'c': 9}

但实际结果是:

{'a': 7, 'b': 8, 'c': 9}
{'a': 7, 'b': 8, 'c': 9}
{'a': 7, 'b': 8, 'c': 9}

要修复这段代码以获得期望的结果,你可以在循环内部创建新的字典,而不是多次使用同一个字典。以下是修复后的代码:

data = []

for i in range(1, 10, 3):
    dic = {'a': i, 'b': i + 1, 'c': i + 2}
    data.append(dic)

for i in data:
    print(i)

这将产生期望的输出:

{'a': 1, 'b': 2, 'c': 3}
{'a': 4, 'b': 5, 'c': 6}
{'a': 7, 'b': 8, 'c': 9}
英文:
data = []
dic = dict.fromkeys(['a', 'b', 'c'], 0)

value = 1
for i in range(3):
    key = list(dic.keys())
    for j in range(len(dic)):
        dic[key[j]] = value
        value += 1
    data.append(dic)
    
for i in data:
    print(i)

In this code, I expexted like this.

{1, 2, 3}
{4, 5, 6}
{7, 8, 9}

but the result is

{7, 8, 9}
{7, 8, 9}
{7, 8, 9}

How can i fix this code to get result that i expected?

答案1

得分: 1

你只有一个字典,dic。你已经创建了一个包含对它的三个引用的列表。为了获得你想要的结果,更改你的代码,使其在主循环的每次迭代中创建一个新的字典。

英文:

You only have one dictionary, dic. You have created a list with three references to it. To get the results you want, change your code to create a new dictionary for each iteration of the main loop

答案2

得分: 0

使用:

data.append(dic.copy())

这将创建一个新的对象,而不是将对 dic 的引用添加到您的列表中。

英文:

Instead of :

    data.append(dic)

Use:

    data.append(dic.copy())

This will create a new object, instead of adding a reference to dic to your list.

huangapple
  • 本文由 发表于 2023年7月31日 23:02:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76804884.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定