【发布时间】:2021-04-17 23:21:42
【问题描述】:
我的循环有一个输出,其中 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'), ('45', '39'), ('45', '24'), ('45', '81'), ('45', '29'), ('45', '46'), ('45', '51'), ('45', '23'), ('45', '8'), ('45', '60'), ('45', '83'), ('45', '86'), ('45', '149'), ('45', '18'), ('45', '99'), ('45', '78'), ('45', '120'), ('45', '134'), ('45', '121'), ('45', '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,k) for k,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, k) for k,v in nx.shortest_path_length(G,
node).items() if v == 2]
print(start_end_nodes)
Out:
[(1, 3)]
[(2, 1), (2, 4)]
[(4, 1)]
[(3, 2)]
【问题讨论】:
-
您可能想检查
nx.shortest_path_length(G, node)及其items()返回的内容。 -
dict_items([元组,元组,元组..])? TypeError: 'dict_items' 对象不可下标
-
这看起来像是一个按长度排序的问题,不是吗?
标签: python list loops list-comprehension networkx