使用嵌套字典Python的自定义类 [英] Custom class using nested dictionary Python

查看:68
本文介绍了使用嵌套字典Python的自定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用相同的键在嵌套字典中添加值时,我遇到一个问题,并且该值始终显示为相同的值,事实是,我想要更新键相同的值事件.该算法是人工鱼群算法的基础

I have a problem when adding value inside the nested dictionary using the same keys and the value is always shown the same value, The fact is, i want update the value event the keys is same. This algorithm is the basic of Artificial Fish Swarm Algorithm

# example >> fish_template = {0:{'weight':3.1,'visual':2,'step':1},1:'weight':3,'visual':4,'step':2}}

fish = {}
fish_value = {}
weight = [3.1, 3, 4.1, 10]
visual = [2, 4, 10, 3]
step = [1, 2, 5, 1.5]

len_fish = 4

for i in range(0,len_fish):
  for w, v, s in zip(weight, visual, step):
     fish_value["weight"] = w
     fish_value["visual"] = v
     fish_value["step"] = s
     fish[i] = fish_value

  print("show fish",fish)

我希望结果类似于fish_template,但事实并非如此.按键"weight","visual","step"的值始终相同,分别为0、1、2和3.有解决方案吗?

I expect the result to be like fish_template, but it isn't. The values for the keys 'weight', 'visual', 'step' are always the same with values of 0, 1, 2, and 3. Any solution?

推荐答案

问题出在 fish [i] 上,您只需创建一个具有相同元素的 dict : fish_value .Python不会为相同的变量名生成新的内存,因此您所有的dict键都指向相同的value = fish_value ,该值将被覆盖,并且所有dict值都将采用 fish_value的最后状态.为了克服这个问题,您可以执行以下操作:

The issue is with fish[i], you simply created a dict with the same element: fish_value. Python does not generate a new memory for the same variable name, so all your dict keys point to the same value=fish_value, which gets overwritten and all your dict values take the last state of fish_value. To overcome this, you can do the following:

fish   = {}
weight = [3.1, 3, 4.1, 10]
visual = [2, 4, 10, 3]
step   = [1, 2, 5, 1.5]

len_fish = 4

for i in range(0, len_fish):
     fish[i]= {"weight": weight[i], "visual": visual[i], "step": step[i]}

print("show fish", fish)

如@Error所述,for循环可以替换为以下这种单行代码:

As @Error mentioned, the for loop can be replaced by this one-liner:

fish = dict((i, {"weight": weight[i], "visual": visual[i], "step": step[i]}) for i in range(len_fish))

这篇关于使用嵌套字典Python的自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆