我没有单独获取列表项

时间:2015-05-06 09:23:16

标签: python networkx

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']

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分: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