Python 我想找到二维列表之间的距离,然后将其添加到元素中
我的数据如下:Python 我想找到二维列表之间的距离,然后将其添加到元素中,python,Python,我的数据如下: mx_ranges1 = [ (848,888), (806,848), (764,806), (722,764), (680,722), (638,680), (596,638), (554,596), (512,554), (470,512), (428,470), (386,428), (344,386), (302,344), (260,302), (218,260), (176,218), (13
mx_ranges1 = [
(848,888),
(806,848),
(764,806),
(722,764),
(680,722),
(638,680),
(596,638),
(554,596),
(512,554),
(470,512),
(428,470),
(386,428),
(344,386),
(302,344),
(260,302),
(218,260),
(176,218),
(134,176),
]
a=((mx_ranges1[0][1]-mx_ranges1[0][0])/2)+(mx_ranges1[0][0])
b=((mx_ranges1[1][1]-mx_ranges1[1][0])/2)+(mx_ranges1[1][0])
c=((mx_ranges1[2][1]-mx_ranges1[2][0])/2)+(mx_ranges1[3][0])
print(a)
print(b)
print(c)`
这种方法并不是很有效,我知道它可以以某种方式表示在for
循环中,我只是不知道如何才能做到。请给我一些参考资料,因为我是python和编程新手。然后我有另一个列表,其中y也需要计算距离,然后将其添加到第一个元素中
不确定它是否可以直接放置到单个2D阵列中,但对我来说,只做第一部分就足够了。我可以手动完成其余部分。您可以使用一个简单的:
这相当于以下for循环:
res = []
for i,j in mx_ranges1:
res.append((j-i)/2 + i)
您还提到使用numpy数组。请注意,这将是最有效和最简单的方法,因为这是一个问题:
Numpy会快得多
import numpy as np
mx_ranges1 = [
(848,888),
(806,848),
(764,806),
(722,764),
(680,722),
(638,680),
(596,638),
(554,596),
(512,554),
(470,512),
(428,470),
(386,428),
(344,386),
(302,344),
(260,302),
(218,260),
(176,218),
(134,176),
]
a = np.array(mx_ranges1)
# the first index accessor : says all rows, the second specifies a column
result = (a[:,1] - a[:,0])/2 + a[:,0]
# result contains one value for each row/tuple in `mx_ranges1`
print(result)
这将返回:
[868. 827. 785. 743. 701. 659. 617. 575. 533. 491. 449. 407. 365. 323.
281. 239. 197. 155.]
它为输入2D数组的每一行包含一个值。所以868=888-848/2+848。我假设
mx\u ranges1[3][0]
是一个打字错误,应该读mx\u ranges1[2][0]
——对吗?很好!我想我会选择numpy方法,它对我来说最有意义。那么“:”有点像一个索引?那么它会变成0,1,2,3,4…?是的,它是一个指数。查看附加链接以了解更多信息
import numpy as np
mx_ranges1 = [
(848,888),
(806,848),
(764,806),
(722,764),
(680,722),
(638,680),
(596,638),
(554,596),
(512,554),
(470,512),
(428,470),
(386,428),
(344,386),
(302,344),
(260,302),
(218,260),
(176,218),
(134,176),
]
a = np.array(mx_ranges1)
# the first index accessor : says all rows, the second specifies a column
result = (a[:,1] - a[:,0])/2 + a[:,0]
# result contains one value for each row/tuple in `mx_ranges1`
print(result)
[868. 827. 785. 743. 701. 659. 617. 575. 533. 491. 449. 407. 365. 323.
281. 239. 197. 155.]