如何从python networkX中的列表列表中访问元素?类型错误:“int”对象不可迭代

问题描述

我的循环有一个输出,其中 G 是 networkX 的图。

for node in G.nodes():
    start_end = [(node,k) for k,v in nx.shortest_path_length(G,node).items() if v == d]
    print (start_end)

这是很多包含元组的列表类。 (如果只是一个列表,做 start_end[0][0] 会很容易。)

<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
....
[]
[]
[]
[]
[]
[]
[('45','27'),('45','26'),'39'),'24'),'81'),'29'),'46'),'51'),'23'),'8'),'60'),'83'),'86'),'149'),'18'),'99'),'78'),'120'),'134'),'121'),'122')]
[]
[]
[]
[]
[]
[]
[('129','134')]
[]
[('134','92'),('134','97')]
[]
[]
[]
[]
[]

在本例中,我想获取最长列表 '45' 的第一个元素。 我试图按长度对列表进行排序。

sorted(start_end,reverse=True)
max(start_end)

产生错误

#TypeError: 'int' object is not iterable

我也试过

start_end = len([(node,v in nx.shortest_path_length(G_sc,node).items() if v == d])
print(max(current))

同样的错误

以下是您可以重现的伪代码在这里,我如何从第二个(最长的)列表中访问元组 ((2,1)?

In: 
import networkx as nx
G = nx.DiGraph()

G.add_edge(1,2); G.add_edge(1,4)
G.add_edge(3,1); G.add_edge(3,4)
G.add_edge(2,3); G.add_edge(4,3)

for node in G.nodes():
    start_end_nodes = [(node,node).items() if v == 2]
    
    print(start_end_nodes)

Out:
[(1,3)]
[(2,1),(2,4)]
[(4,1)]
[(3,2)]

解决方法

有人通过创建一个空字典向我推荐了这个版本。 所以我试图了解它是如何工作的,更具体地说,'scores[node] = end_node,以及它是否比你的更好(更快)。

def f2(G):        
    scores = {}
    d = 2
            
    for node in G.nodes():
        shortest = nx.shortest_path_length(G_sc,node)
        end_node = len([k for k,v in shortest.items() if v == d])
        scores[node] = end_node
    return ((max(scores))