【问题标题】:Closest Pair Algorithm in Python: difficulty sorting by x and y coordinatesPython 中的最近对算法:按 x 和 y 坐标排序的难度
【发布时间】:2018-11-22 09:28:30
【问题描述】:

我正在尝试定义一个函数,该函数将一个数组作为输入,该数组由具有 x 和 y 坐标的点组成。我需要 2 个输出:一个数组的点按 x 坐标排序,另一个数组的点按 y 坐标排序。我正在用python做。谢谢。

【问题讨论】:

  • 向我们展示您已经拥有的东西以及您遇到的问题,我们可以向您展示如何摆脱困境。没有任何细节,我能做的最好的就是在文档中指向Key Functions。您可以编写一个关键函数,或者只使用itemgetterattrgetter(取决于您表示点的方式),如示例中所示。
  • 同时,为什么这被标记为mergesortalgorithm?你是在编写自己的归并排序函数,而不是使用 Python 的 sortsorted

标签: python python-3.x algorithm sorting mergesort


【解决方案1】:

或者,您可以使用 itemgetter() 函数作为 sorted() 函数的 key 参数:

from operator import itemgetter

points = [(7,3), (2,1), (4,5), (9,0)]
sorted_by_x = sorted(points) # you can add the key parameter itemgetter(0) if you want
sorted_by_y = sorted(points, key=itemgetter(1))

print("Points List: {}".format(points))
print("Sorted by X Points List: {}".format(sorted_by_x))
print("Sorted by Y Points List: {}".format(sorted_by_y))

输出:

Points List: [(7, 3), (2, 1), (4, 5), (9, 0)]
Sorted by X Points List: [(2, 1), (4, 5), (7, 3), (9, 0)]
Sorted by Y Points List: [(9, 0), (2, 1), (7, 3), (4, 5)]

【讨论】:

    【解决方案2】:

    我将假设您的数组如下所示:

    input = [(1,2), (3,4), ..., (x,y)]
    

    您可以使用sorted方法(内置)来完成列表排序:

    x_sorted = sorted(input, key=lambda tup: tup[0])
    y_sorted = sorted(input, key=lambda tup: tup[1])
    

    lambda 将分别按第一个和第二个索引对变量进行排序

    【讨论】:

    • 您的解释指向sort 方法,但您的示例使用sorted 函数。
    猜你喜欢
    • 2014-11-06
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2012-06-02
    • 1970-01-01
    • 2016-08-02
    相关资源
    最近更新 更多