2014-05-24 142 views
0

我写了这段代码,我需要一些帮助来调试它。我不得不说,我在这方面本网站看了一些类似的话题,但它不能帮我调试我的代码:)将字典追加到循环中的另一个字典

OUTPUT:

Number of max devices per route: 4 
Number of routes: 2 
Level of mobility: 2 
routes at T 0 : {0: [28, 14, 7, 4], 1: [22, 0]} 
routes at T 1 : {0: [29, 20, 28], 1: [28]} 
{0: {0: [29, 20, 28], 1: [28]}, 1: {0: [29, 20, 28], 1: [28]}} 

我的问题是,我想有这样的输出:

{ 0:{0: [28, 14, 7, 4], 1: [22, 0]} , 1: {0: [29, 20, 28], 1: [28]},} 

但是,我不知道为什么最后一本字典在新字典中再次重复。我试图调试它,但我无法成功。那么,我怎样才能将字典附加到循环中的另一个字典?

class myClassName(object): 
    def __init__(self): 
     """ 
     Class constructor. 
     """ 

     self.no_devices = input("Number of max devices per route: ") 
     self.no_routes = input("Number of routes: ") 
     self.mob=input("Level of mobility: ") 
     self.all_routes={} 
     self.routes = {} 

     self.arr = [0,1,2,3,4,5,6,7,8,9,10...,29] 

     for j in xrange(self.mob): 
      for i in range(self.no_routes): 
       random.shuffle(self.arr)           
       self.routes[i] = list(self.arr[0: random.randint(1,self.no_devices)])   
       self.all_routes[j]=self.routes 


      print "routes at T" ,j, ":" ,self.routes 


     print self.all_routes 
+0

如何初始化'self.arr'。在分配任何价值之前它似乎被洗牌了?在没有完整信息的情况下调试代码非常困难。 – Marcin

+0

嗨,谢谢你的回复,self.arr是一个数组,包括0到29之间的数字。 – user3671039

回答

0

由于@shaktimaan指示self.routes在循环的每次迭代中被覆盖,并且self.all_routes仅保留对self.routes的引用。我修改了代码,一次使它与python 3.4(即我的Python版本,对不起,我现在不使用2.x)以及解决覆盖问题。

import random 

class myClassName(object): 
    def __init__(self): 
     """ 
     Class constructor. 
     """ 

     self.no_devices = int(input("Number of max devices per route: ")) 
     self.no_routes = int(input("Number of routes: ")) 
     self.mob = int(input("Level of mobility: ")) 
     self.all_routes={} 


     self.arr = list(range(0,30)) 

     for j in range(self.mob): 
      routes = {} 
      for i in range(self.no_routes): 
       random.shuffle(self.arr)           
       routes[i] = list(self.arr[0: random.randint(1,self.no_devices)])   
       self.all_routes[j]=routes 


      print("routes at T" ,j, ":" ,routes) 


     print(self.all_routes) 



if __name__ == '__main__': 
    myClassName() 

输出示例:

Number of max devices per route: 4 
Number of routes: 2 
2Level of mobility: 
routes at T 0 : {0: [0, 10], 1: [22, 14]} 
routes at T 1 : {0: [16], 1: [22, 3, 5, 17]} 
{0: {0: [0, 10], 1: [22, 14]}, 1: {0: [16], 1: [22, 3, 5, 17]}} 

希望这将是对你有用。

+0

非常感谢。它的工作原理 – user3671039

+0

@ user3671039很高兴能帮到你。如果答案是令人满意的,接受它将不胜感激。 – Marcin

0

你可以这样做: orig_dict.update(new_dict)

注:

我想:如果两个字典有一些类似的按键,该值将从new_dict

编辑采摘您可能遇到的问题是因为您正在用list覆盖dictroutes & all_routes

+0

tnx for reply。但我不想更新它,我想追加第一个和第二个路线字典到新的。在每次迭代中,我有一个新的路由字典,我想追加所有新的字典包含所有... – user3671039