我有一个来自循环的输出,其中G是来自networkX的Graph。
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)]
解决此问题的一种方法是将所有start_end
值存储在列表start_ends
-中,然后根据len
:获得最大值
max(start_ends, key=len)
完整代码
def f2(G):
start_ends = []
d = 2
for node in G.nodes():
start_end = [(node, k) for k,v in nx.shortest_path_length(G, node).items() if v == d]
start_ends.append(start_end)
#print(max(start_ends, key=len)[0])
return max(start_ends, key=len)[0]
对于图形:
#In:
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)
f2(G)
#Out:
(2, 1)
选项2:
你也可以使用sorted
来获得同样的效果,但如果你想对列表进行排序,而不仅仅是最大,我建议你使用它
# to sort use:
start_ends_sorted = sorted(start_ends, key=len, reverse=True)
# to get the same result as before:
start_ends_max = start_ends_sorted[0][0]
# ---------------
# In your example:
start_ends_sorted = [[(2, 1), (2, 4)],
[(1, 3)],
[(4, 1)],
[(3, 2)]]
start_ends_max = (2, 1)
有人通过创建一个空字典向我推荐了这个版本。因此,我试图了解这是如何工作的,更具体地说,这行的分数[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))