python - 在 map 上划分长度为 1 的部分

标签 python arrays algorithm

我有这些坐标:

coord = [(10,10), (13,10), (13,13)]

现在我需要新坐标。 两个坐标之间的方式总是一个。 例如:

(10,10)
(11,10)
(12,10)
(13,10)
(13,11)
(13,12)
(13,13)

有什么想法吗?

#

我找到了解决方案。

for n in range(len(coord)-1):
    lengthx = coord[n+1][0] - coord[n][0]
    lengthy = coord[n+1][1] - coord[n][1]
    length = (lengthx**2 + lengthy**2)**.5
    for m in range(length):
        print coord[n][0]+lengthx/length*m, coord[n][1]+lengthy/length*m

最佳答案

Bresenham's line algorithm 的简单变体将仅使用整数运算来实现您想要的(因此它应该明显更快):

def steps(path):
    if len(path) > 0:
        for i in range(1, len(path)):
            for step in steps_between(path[i - 1], path[i]):
                yield step
        yield path[-1]


def steps_between(start, end):
    x0, y0 = start
    x1, y1 = end

    steep = abs(y1 - y0) > abs(x1 - x0)
    if steep:
        x0, y0 = y0, x0
        x1, y1 = y1, x1

    if y0 > y1:
        x0, x1 = x1, x0
        y0, y1 = y1, y0

    if y0 < y1:
        ystep = 1
    else:
        ystep = -1

    deltax = x1 - x0
    deltay = abs(y1 - y0)
    error = -deltax / 2

    y = y0
    for x in range(x0, x1):
        if steep:
            yield (y, x)
        else:
            yield (x, y)

        error += deltay
        if error > 0:
            y += ystep
            error -= deltax
            if steep:
                yield (y, x)
            else:
                yield (x, y)

coords = [(10, 10), (13, 10), (13, 13)]
print "\n".join(str(step) for step in steps(coords))

上面的打印:

(10, 10)
(11, 10)
(12, 10)
(13, 10)
(13, 11)
(13, 12)
(13, 13)

当然,当 xy 在路径上的两点之间变化时,Bresenham 会按预期工作:

coords = [(10, 10), (13, 12), (15, 13)]
print "\n".join(str(step) for step in steps(coords))

打印:

(10, 10)
(11, 10)
(11, 11)
(12, 11)
(12, 12)
(13, 12)
(14, 12)
(14, 13)
(15, 13)

关于python - 在 map 上划分长度为 1 的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4977637/

相关文章:

python - 如何在 PySpark 中分别对多个列进行透视

python - Tarfile/Zipfile extractall() 更改某些文件的文件名

Python - 获取所有目录的文件扩展名

java - 将 2 维数组中的一行的 MIN 和 MAX 值存储在 1 维数组中?

algorithm - 查找二维数组中所有峰的高效算法

python - sp-api - 卖家合作伙伴api python

c - 为什么这会提前停止运行?

algorithm - 根据高度重新排列人员的算法是否正确?

c++ - 超长冗余代码高效吗?

arrays - PowerShell:将十六进制变量转换为单个(float32)大端变量