如何在Python 2.7中找到元组列表中最后两个索引之间的所有距离组合



如果我有这样的列表:

mList = [[[4,3,2], [65,24,34]], 
[[424,242,234]],[[42323,2432,234]], 
[[24,234,2442],[24,1213,1231]]]

其中

m1 is sub-list [[4,3,2], [65,24,34]]
where m1p1=[4,3,2]
m1p2=[65,24,34]
m2 is sub-list  [[424,242,234]],[[42323,2432,234]] 
where m2p1=[424,242,234]
m2p2=[42323,2432,234]
m3 is sub-list [[24,234,2442],[24,1213,1231]] 
where m3p1=[24,234,2442]
m3p2=[24,1213,1231]

m1m2m3中的列表中的三个元素是[x坐标,y坐标,时间],例如,对于m3p1,x坐标是24,y坐标是234,时间是2442,但时间与我的问题无关。

我需要编写一个程序,从mList的最后两个索引(现在是m2和m3)中获取所有x和y坐标,并在所有这些x和y点之间创建长度以存储在列表中

因此,在不同的子列表m2和m3中,以(m2p1和m3p1)、(m2p2和m3p1、(m2p1与m3p2)、(m2p2和m3p2)的组合仅在x坐标和y坐标之间计算长度,而在某个子列表m2或m3中,不在p1和p2之间计算长度(m2p1 and m2p2),并且不计算(m3p1和m3p2)长度。

我可以使用math.hyp()公式计算长度,但我需要一个for循环,即使在m2或m3中添加了更多项(如m2p3、m3p3、m3p4),或者在mList中添加了其他项(如m4、m5),它也能起作用。有人能帮忙吗?谢谢

for i in mList:
for j in i:
for k in mList:
if k != i:
for l in k:
put the code to compare j with l here.

你是这个意思吗?

这就是您所需要的:

import math
# configurable list
mList = [[[4,3,2], [65,24,34]], 
[[424,242,234],[42323,2432,234]],
[[24,234,2442],[24,1213,1231]]]
# list to contain the result
distanceList = []
# m1 and m2 the last 2 elements
m1 = mList[-1]
m2 = mList[-2]
for mp1 in m1:
for mp2 in m2:
# addend the length between the x and y
distanceList.append([math.hypot(mp1[0], mp2[0]), math.hypot(mp1[1], mp2[1])])
print distanceList

最新更新