【问题标题】:Finding the middle point of a given list of coordinates [duplicate]查找给定坐标列表的中点[重复]
【发布时间】:2022-01-11 05:57:21
【问题描述】:

我需要写def middle_point(coordinates),每次都会给我一个坐标列表(元组),它应该返回一个元组。

例如:

coordinates = [(2,4),(2,0)] 我需要返回 (2,2)

或其他时间:

coordinates = [(2, 8, 7, 5), (6, 10, 1, 3), (1, 1, 4, 6)] 我需要返回 (3, 6.3, 4, 4.7)

我知道我需要使用哪个公式,但我不知道如何到达那里。

【问题讨论】:

  • 如果你知道你需要使用的公式,有什么问题?
  • 好吧,所有坐标都在一个列表中给出,而不是单独的元组,所以我不知道如何相应地获取每个坐标。我不知道如何加起来:第一个示例为 (x1+x2) 或第二个示例为 (x1+x2+x3)。
  • 如果你可以使用numpy,简单的方法是转换为numpy数组,使用np.average和axis=0,如果需要,将输出转换回元组。
  • 需要更多详细信息来说明您想要实现的目标以及到目前为止您已经尝试过的目标。请阅读本指南:stackoverflow.com/help/how-to-ask
  • 我编辑了我的帖子,使其更全面。

标签: python list tuples


【解决方案1】:

你可以使用 zip。

coordinates = [(2, 8, 7, 5), (6, 10, 1, 3), (1, 1, 4, 6)]

result = [sum(x)/len(x) for x in zip(*coordinates)]

【讨论】:

  • 这是一个很酷的方法 - 使用zip 来旋转矩阵:D
  • 感谢您的帮助,现在我知道了 '*' 的含义。我以前没见过。
【解决方案2】:
l = len(coordinates[0]) # Length of each coord
results = [0] * l # Convert to tuple at end

for coordinate in coordinates:
    for i in range(l):
        results[i] += coordinate[i] / l # Averaging points beforehand

results = tuple(results)

【讨论】:

  • “results = [0] * l”这一行是什么意思?
  • 它只是预先生成了0 的l 元素的列表 - 例如,与在 C# 中初始化列表相同。
【解决方案3】:

您可以将矩阵旋转 90 度并返回每行的平均值。

import numpy as np

q = [(2, 8, 7, 5), (6, 10, 1, 3), (1, 1, 4, 6)]

answer = [round(sum(x)/len(x),1) for x in np.rot90(q)][::-1]

print(answer)

或者你可以使用np.average() 来做所有事情

 print(np.average(q, axis=0))

【讨论】:

  • 感谢您的代码,尽管由于某种原因我不能使用 numpy。当我弄清楚如何使用它时,我会彻底查看代码。
猜你喜欢
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
  • 1970-01-01
  • 2018-07-30
  • 2015-11-10
  • 2021-07-19
  • 1970-01-01
  • 2016-01-28
相关资源
最近更新 更多