在Python中将for循环转换为lambda / list理解

我有一个列表loc_combinations,其长度为91806,其唯一ID对的结构如下:

[(1,2), (1,3), 1,4)...(452, 454)]

I am trying to apply the same function distance_calculator to each pair in the list which returns a single value, the distance. I was able to get my answer using a for loop but was hoping someone could show me how to do it using Lambda and list comprehension.

这是for循环:

distance_list = []
for i in range(len(loc_combinations)): 
    distance_list.append(distance_calculator(id1 = loc_combinations[i][0], id2 = loc_combinations[i][1]))
评论
  • uharum
    uharum 回复

    如果定义了工作函数,则不需要lambda函数。您的代码作为列表理解如下所示:

    distance list = [distance_calculator(x[0], x[1]) for x in loc_combinations]