我正在尝试使用循环填充字典,问题是在完成条件后循环停止而不检查是否有更多可用条件要实现,
sec=[
[1, 2, 4.0, 100.0],
[2, 3, 1.5, 500.0],
[2, 4, 10.0, 700.0],
[2, 5, 5.75, 1500.0],
[3, 4, 11.4, 200.0],
[4, 5, 10.5, 750.0],
[4, 6, 6.75, 550.0]]
我制作了这个列表,还有这本词典
graph={1: [1], 2: [2], 3: [3], 4: [4], 5: [5], 6: [6]}
我想要完成的是
graph = {1: ['2'],
2: ['3', '4','5'],
3: ['4'],
4: ['5','6'],
5: [],
6: []}
它应该如何工作是它收集所有sec[x][0]
作为字典的键,sec[n][1]
作为字典中的值
如果sec [x] [0]的值为1且sec [x] [1]的值为2,则将数字2作为键1的值添加到字典中
我得到的代码就是这个
def magic(numList): #turns string into int
s = ''.join(map(str, numList))
return int(s)
for i in range(1,len(loc)+1): #len of loc is 6
for n in range(0,len(loc)+1):
if magic(graph[i])==sec[n][0]:
graph[i].append(sec[n][1])
但它只会添加第一个值,然后索引n将停止计数,然后索引i继续运行,因此它不会检查键中的更多值
答案 0 :(得分:4)
graph
的初始定义对预期结果没有帮助。使用空列表初始化值,然后附加到一个简单的循环中:
>>> sec=[
[1, 2, 4.0, 100.0],
[2, 3, 1.5, 500.0],
[2, 4, 10.0, 700.0],
[2, 5, 5.75, 1500.0],
[3, 4, 11.4, 200.0],
[4, 5, 10.5, 750.0],
[4, 6, 6.75, 550.0]]
>>> graph = {i:[] for i in range(1,7)}
>>> for x,y,*z in sec: graph[x].append(str(y))
>>> graph
{1: ['2'], 2: ['3', '4', '5'], 3: ['4'], 4: ['5', '6'], 5: [], 6: []}
答案 1 :(得分:0)
使用collections模块中的defaultdict。见下文:
from collections import defaultdict
graph_dd = defaultdict(list)
for s in sec:
from_, to_ = s[:2]
graph_dd[from_].append(to_)
# do-nothing reference to to_ creates empty list, so that all nodes are represented
# in graph_dd; else 5 and 6 would not be created
graph_dd[to_]
# convert to regular dict (not really necessary, but OP wanted a dict)
graph = dict(graph_dd.items())
for k,v in graph.items():
print(k,':', v)
打印:
1 : [2]
2 : [3, 4, 5]
3 : [4]
4 : [5, 6]
5 : []
6 : []