如何将多个参数传递给sorted()的方法'key'?

Tho*_*hom 5 python sorting django

在网站上,我试图根据用户的相对位置对商店列表进行排序.让我解释.

一家商店看起来像这样:

class Shop(models.Model):
    latitude = models.DecimalField(max_digits=9, decimal_places=6)
    longitude = models.DecimalField(max_digits=9, decimal_places=6)
Run Code Online (Sandbox Code Playgroud)

我在会话中获得用户的位置.

request.session['user_latitude']
request.session['user_longitude']
Run Code Online (Sandbox Code Playgroud)

所以现在我得到了一个商店列表,我想对它们进行排序.所以我尝试了这个:

def distance_of_the_shop(shop):
    # compute the distance between the shop and the user and return it
    return computed_distance

sorted(shop_list, key=distance_of_the_shop)
Run Code Online (Sandbox Code Playgroud)

问题很简单,如何将多个参数传递给方法distance_of_the_shop

Mar*_*ers 14

只需将调用包装在lambda中:

ulong, ulat = request.session['user_latitude'], request.session['user_longitude']
sorted(shop_list, key=lambda shop: distance_of_the_shop(shop, ulong, ulat))
Run Code Online (Sandbox Code Playgroud)

并向distance_of_the_shop()函数添加两个参数以接收经度和纬度.

sorted()函数调用keyfor中的每个值shop_list,但没有任何内容表示callable本身不能调用其他函数.A lambda是创建新包装函数的最简单方法.

您也可以使用functools.partial()对象,前提是经度和纬度值可以作为关键字参数传递,或者将这两个值作为前两个位置参数接受.将它们作为关键字参数处理可能是最好的,即使它们被赋予一个位置(没有默认值),您也可以将它们的名称用作关键字参数partial().

假设定义是:

def distance_of_the_shop(shop, long, lat):
    # ...
Run Code Online (Sandbox Code Playgroud)

然后用

sorted(shop_list, key=partial(distance_of_the_shop, long=ulong, lat=ulat))
Run Code Online (Sandbox Code Playgroud)

并将sorted()每个传递shoppartial(),然后调用distance_of_the_shop(shop, long=ulong, lat=ulat)