有没有更好的方法来编写这个函数?
def highest_strength(G):
highest_strength = None
highest_strength_val = 1
for node1 in G:
for node2 in G[node1]:
val = G[node1][node2]
if val > highest_strength_val:
highest_strength_val = val
highest_strength = (node1, node2)
return highest_strength
答案 0 :(得分:4)
很简单:
def highest_strength(graph):
return max((s, x, y) for x, links in graph.items() for y, s in links.items())
它是如何运作的:
>>> highest_strength(graph)
(4, 'c', 'b')
扩展版本:
def highest_strength(G):
best_strength, best_link = None, (None, None)
for x, links in G.items():
for y, v in links.items():
if v > best_strength:
best_strength, best_link = v, (x, y)
return best_link