我的数据结构定义如下:
reqList[i] = [multidict({
1: ['type1', randint(1, 5), randint(1, 5), randint(1, 5)],
2: ['type2', randint(1, 5), randint(1, 5), randint(1, 5)],
3: ['type3', randint(1, 5), randint(1, 5), randint(1, 5)],
4: ['type4', randint(1, 5), randint(1, 5), randint(1, 5)]
}),
multidict({
(1, 2): randint(500, 1000),
(2, 3): randint(500, 1000),
(3, 4): randint(500, 1000)
})]
我想在for循环中自动创建这个数据结构,例如。我这样做了:
nodes = {}
for j in range(1, randint(2, 5)):
nodes[j] = ['type%d' % j, randint(1, 5), randint(1, 5), randint(1, 5)]
edges = {}
for kk in range(1, len(nodes)):
edges[(kk, kk + 1)] = randint(500, 1000)
print "EDGES", edges
reqList[i] = [multidict(nodes),
multidict(edges)]
del (nodes, edges)
当我查看输出的边缘时,键的顺序不会被保留!例如,我得到了这个:
EDGES {(1, 2): 583, (3, 4): 504, (2, 3): 993}
我希望它是:
EDGES {(1, 2): 583, (2, 3): 993, (3, 4): 504}
我编码的方式是否正确?如果没有,你能否提出一个更好的方法,知道我需要得到与第一个例子中相同的结果?
答案 0 :(得分:0)
2.7中的词典是无序的,你不能保持插入的顺序,除非你手动保持对插入的键和在单独的列表中的引用。模块collections
包含一个名为OrderedDict
的类,其作用类似于字典,但保持插入有序,这是您可以使用的(它还使用列表来跟踪键插入但使用了双链接列表,以加快删除键)。
除了这两种方法之外别无他法。
from collections import OrderedDict
nodes = {}
for j in range(1, randint(2, 5)):
nodes[j] = ['type%d' % j, randint(1, 5), randint(1, 5), randint(1, 5)]
edges = OrderedDict()
for kk in range(1, len(nodes)):
edges[(kk, kk + 1)] = randint(500, 1000)
print "EDGES", edges # EDGES OrderedDict([((1, 2), 898), ((2, 3), 814)])
print edges[(1,2)] # still yields the correct number
您可以阅读有关OrderedDict
here