我想找到地图上许多(~6000)个地方之间的所有距离。为此,我使用Mapbox's Distance API,它获取最多100个坐标对的列表,并返回它们之间的距离矩阵。 所以,如果你给它:
{
"coordinates": [
[13.41894, 52.50055],
[14.10293, 52.50055],
[13.50116, 53.10293]
]
}
它将返回如下矩阵:
{
"durations": [
["A to A", "A to B", "A to C"],
["B to A", "B to B", "B to C"],
["C to A", "C to B", "C to C"]
]
}
所以,因为我无法向所有6000个地方发送请求,所以我必须分段进行。经过几次尝试,我想出了这个解决方案:
这里使用Python编写玩具代码(没有实际的API调用,位置用数字表示):
import itertools
import random
def get_set(s, rsample_size):
m_set = set([x[0] for x in s] + [x[1] for x in s])
if len(m_set) < rsample_size:
rsample_size = len(m_set)
sampled = random.sample(set(m_set), rsample_size) #sampling
return sampled, rsample_size
#all place features, but just numbers here
master = set(range(500))
#all possible permutations between them
master_combinations = set(itertools.permutations(master, 2))
print 'len of original combinations list', len(master_combinations)
c = 0
#API call limit
smpl_size = 100
while len(master_combinations) > 0:
print 'start iter: ', c, '\t remaining combinations: ', len(master_combinations)
#sampling 100 random locations
combs, smpl_size = get_set(master_combinations, smpl_size)
#a set of all possible permutations of above 100
combs = set(itertools.permutations(combs, 2))
#subtracting calculated pairs from all possible pairs
master_combinations = master_combinations.difference(combs)
c += 1
以上示例在132-140次调用中查找所有可能的500个元素对之间的距离。我有两个问题:
我的问题是,因为我显然是通过该列表强行扼要,是否有更优雅和有效的方法呢?
我想的可能是:
任何想法都将不胜感激。谢谢!