2015-05-06 26 views
0
nodes=['a','b','c','d','e','f','g'] 
G.add_edges_from([('a','f'),('a','d'),('a','b'),('a','e'),('b','g'),('b','e'),('b','c'),('c','b'),('c','d'),('d','a'),('d','c'),('e','b'),('e','a'),('f','a'),('g','b')]) 
nodlen=len(nodes) 
for i in range(nodlen): 
    print(G.neighbors(nodes[i])) 

我得到整個列表(如下所示),但我需要訪問此列表中的各個元素。我沒有單獨獲取列表項目

['e', 'b', 'f', 'd'] 
['e', 'c', 'g', 'a'] 
['b', 'd'] 
['c', 'a'] 
['b', 'a'] 
['a'] 
['b'] 
+1

那麼,爲什麼不使用'gneighbors Python小技巧:當你只能循環訪問列表本身時,不要遍歷'range()':'in node in nodes:','print('Neighbors for {}'.format(node))','for G.neighbors(節點)中的鄰居:','print('',neighbor)'。 –

回答

0
nodes=['a','b','c','d','e','f','g'] 
G.add_edges_from([('a','f'),('a','d'),('a','b'),('a','e'),('b','g'),('b','e'),('b','c'),('c','b'),('c','d'),('d','a'),('d','c'),('e','b'),('e','a'),('f','a'),('g','b')]) 
nodlen=len(nodes) 
for i in range(nodlen): 
    all_items = G.neighbors(nodes[i]) 
    for one in all_items: 
     print one 
2

Graph.neighbors() method返回沼澤標準的Python list對象。只要索引它:

neighbors = G.neighbors(nodes[i]) 
print('First neighbor', neighbors[0]) 

或循環它以獲得列表中的每個單獨的元素。

在Python中,您通常不會生成索引來訪問列表中的所有元素,您只需遍歷列表本身; for構造是Foreach loop

nodes=['a','b','c','d','e','f','g'] 
G.add_edges_from([('a','f'),('a','d'),('a','b'),('a','e'),('b','g'),('b','e'),('b','c'),('c','b'),('c','d'),('d','a'),('d','c'),('e','b'),('e','a'),('f','a'),('g','b')]) 

for node in nodes: 
    print('Neighbors for', node) 
    for neighbor in G.neighbors(node): 
     print(' ', neighbor) 
    print() 
+0

對不起martijn,我想我的問題是不正確的,實際上由個人元素我的意思['e','b','f','d']不是ebf d ....就像那樣...希望你得到了它。我想比較這些集合中的每一個與另一個...... ie ['e','b','f','d']將其與剩餘部分['e','c','g 」, 'A'] [ 'b', 'd'] [ 'C', 'A'] [ 'b', 'A'] [ '一'] [ 'b'] –

+0

@ akhilamahadevan:這聽起來像你正在試圖做一些效率非常低的事情。爲什麼不解釋(在你的問題中)你想做什麼?您可以在嵌套循環中再次循環剩餘的節點*,並獲取每個其他節點的鄰居進行比較,但嵌套循環會導致二次執行,這意味着* slow *。 –

相關問題