【问题标题】:Point (x,y) coordinates sort lower to higher in Python点(x,y)坐标在Python中从低到高排序
【发布时间】:2020-10-05 04:31:13
【问题描述】:

“点”列表中的随机点。像这样:[x,y] = ([3,4],[2,5],[0,7],[8,1])。

但我需要做这些过程;

  • 第一个,我必须对列表中的点进行排序,例如下 Y 和下 X 作为双点。(例如 [1,2],[1,3])。

  • 第二个,如何在列表中进行这样的操作; (Y0-Y1 / X0-X1) 。

这是我的代码;

import numpy as np
points = np.random.randint(0, 9, size=(18,2))
print(points)

【问题讨论】:

  • 我不明白你的排序方法。
  • @Mbo 例如,你有一个像这样的列表 [ [1,2] , [5,4] , [5,5] ,[1,3] ] --> 排序列表有较低的 x 和 y 。像这样: [ [1,2] , [ 1,3] ,[ 5,4],[5,5] ] --> 在这个列表中索引 0 = [1,2] ,索引 1 = [1,3 ] --> 我正在尝试计算 Y0-Y1 / X0-X1 。在这个例子中( 2-3 / 1-1 )。

标签: python list algorithm numpy random


【解决方案1】:

似乎您想使用 X 字段作为主键和 Y 字段作为辅助键对列表进行排序。我为这种排序提供了 lambda 函数,但实际上它是排序函数的默认行为。

不知道如何处理除以零,所以对于垂直段返回None

s =  [ [1,2] , [ 1,3] ,[ 5,4],[5,5] ]
s = sorted(s, key = lambda a: (a[0], a[1]))
#s = sorted(s) should give the same result
print(s)
slopes = [(a[1] - b[1]) / (a[0] - b[0]) if (a[0] - b[0])!=0 else None 
              for a, b in zip(s[:-1], s[1:])]
print(slopes)

[[1, 2], [1, 3], [5, 4], [5, 5]]
[None, 0.25, None]

【讨论】:

    猜你喜欢
    • 2022-11-13
    • 2018-05-15
    • 1970-01-01
    • 2016-08-02
    • 2021-07-16
    • 2012-08-08
    • 2020-08-10
    • 2016-08-12
    • 2022-01-23
    相关资源
    最近更新 更多