Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列表内部列表之间的欧氏距离_Python_Loops_Itertools_Euclidean Distance_Enumerate - Fatal编程技术网

Python 列表内部列表之间的欧氏距离

Python 列表内部列表之间的欧氏距离,python,loops,itertools,euclidean-distance,enumerate,Python,Loops,Itertools,Euclidean Distance,Enumerate,我想计算列表内部列表之间的欧氏距离,若该距离小于阈值,则得到此类列表的最大元素 我的解决方案给了我两个列表之间的距离,但我想让每个列表彼此重叠。基本上,可能是两个循环的解决方案 yhat = [[10 , 15, 200 ,220], [20 , 25, 200 ,230], [30 , 15, 200 ,230], [100 , 150, 230 ,300], [110 , 150, 240 ,300] ] def euclidean(v1, v2): return sum((p-q

我想计算列表内部列表之间的欧氏距离,若该距离小于阈值,则得到此类列表的最大元素

我的解决方案给了我两个列表之间的距离,但我想让每个列表彼此重叠。基本上,可能是两个循环的解决方案

yhat = [[10 , 15, 200 ,220], [20 , 25, 200 ,230], [30 , 15, 200 ,230], [100 , 150, 230 ,300], [110 , 150, 240 ,300] ]

def euclidean(v1, v2):
    return sum((p-q)**2 for p, q in zip(v1, v2)) ** .5

it = iter(yhat)
prev = next(it)
ec =[]
for ind, ele in enumerate(it):
    ec.append(euclidean(ele, prev))
    prev = ele
ec
总而言之,我想要一个新的列表
xhat
,其中包含以下元素:

xhat = [[30 , 35, 200 ,230], [110 , 150, 240 ,300] ]

您可以使用
enumerate
itertools.compositions
使其非常简短:

from itertools import combinations

out = defaultdict(lambda: defaultdict(dict))
for (i, v1), (j, v2) in combinations(enumerate(yhat), 2):
    out.setdefault(i, {})[j] = euclidean(v1, v2)

out
{0: {1: 17.320508075688775, 2: 22.360679774997898, 3: 183.3712082089225, 4: 190.3286631067428}, 
 1: {2: 14.142135623730951, 3: 166.80827317612278, 4: 173.8533865071371}, 
 2: {3: 170.07351351694948, 4: 176.4227876437735}, 
 3: {4: 14.142135623730951}}
where out将输入列表中的索引映射到这些索引处向量之间的距离。 可以获得距离小于阈值的向量的最大元素,如:

for (i, v1), (j, v2) in combinations(enumerate(yhat), 2):
    if euclidean(v1, v2) < threshold:
        out.setdefault(i, {})[j] = (max(v1), max(v2))
out
{0: {1: (220, 230), 2: (220, 230), 3: (220, 300), 4: (220, 300)}, 
 1: {2: (230, 230), 3: (230, 300), 4: (230, 300)}, 
 2: {3: (230, 300), 4: (230, 300)}, 
 3: {4: (300, 300)}}
对于组合中的(i,v1)、(j,v2)(枚举(yhat),2):
如果欧几里德(v1,v2)<阈值:
out.setdefault(i,{})[j]=(max(v1),max(v2))
出来
{0: {1: (220, 230), 2: (220, 230), 3: (220, 300), 4: (220, 300)}, 
1: {2: (230, 230), 3: (230, 300), 4: (230, 300)}, 
2: {3: (230, 300), 4: (230, 300)}, 
3: {4: (300, 300)}}

好的,非常感谢。我如何将这些标记映射到列表元素,并计算每个列表的最大项。。。这有点复杂:(