2016-12-31 265 views
1

我试图填补字典,而使用循环,问题是循环实现的条件没有,如果有,以满足更多的可用条件检查后停止,的Python for循环迭代

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]的值为1,并且sec [x] [1]的值为2,则会收集所有sec[x][0]作为词典的关键字,sec[n][1]作为词典 中的值,然后添加编号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停止计数,然后指数我不断去,所以它不会检查更键中的数值

+1

很难说为什么代码不会不知道什么恰当地命名为'magic'功能正在做的工作。另外,那些应该是字符串列表? –

+0

抱歉忘了提及, DEF魔法(numList):#turns字符串转换成int S = ''。加入(地图(STR,numList)) 返回INT(S) 基本上变成串入一个int值 – Enigma

回答

4

您对的初始定义对预期结果没有帮助。用空列表初始化值,然后在简单循环中追加:

>>> 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: []} 
+0

可能值得一提的是'defaultdict(list)' – roganjosh

+0

@roganjosh也许吧,但是你不会有这些'[]'。 –

+0

注意:'* z'只适用于Python 3.x;对于旧版本,请使用'for x,y,_,_' –

0

使用集合模块中的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 : []