Python: 将一些参数传递给函数参数

Python: passing some arguments to a function-argunment

我的问题类似于this one。假设我想使用 sklearn.metrics.pairwise.

中的函数 pairwise_distances
def network_analysis(G):
    pairwise_distances(G.nodes, G.nodes, metric=my_metric)
    # blah blah
    #

我有

 def my_metric(x,y,G):
     return networkx.shortest_path(G,x,y)* (G.nodes[x]['weight']-G.nodes[y]['weight'])

但是我不知道如何在 pairwise_distances 调用中将 G 传递给我的指标。

附带说明一下,这是我在使用 Networkx 时遇到的一个问题,因为节点是由数字标识的,对于每个需要使用节点属性的函数,我必须通过整个网络。

假设您无法更改 pairwise_distances,请尝试使用 functools.partial。这允许您执行以下操作:

import functools

def network_analysis(G_input):
    new_metric = functools.partial(my_metric, G = G_input)
    pairwise_distances(G_input.nodes, G_input.nodes, metric = new_metric)
    

New-metric 行为如下:

def new_metric(x, y):
    return my_metric(x, y, G)  # G has already been passed in via functools.partial