我写了这段代码,我需要一些帮助对其进行调试。我不得不说,我已经在此网站上阅读了与此类似的主题,但是它无法帮助我调试代码:)
输出:
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
正如@shaktimaanself.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]}}
希望这对您有用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句