python - 在 Python 中填写坐标列表
问题描述
我有一个排序的坐标列表,例如
coords = [[19, 52], [20, 52], [24, 52], [25, 52], [20, 53], [22, 53], [20, 54], [21, 54]]
我想填写“之间”的坐标,这样结果列表是:
result = [[19, 52], [20, 52], [21, 52], [22, 52], [23, 52], [24, 52], [25, 52], [20, 53], [21, 53], [22, 53], [20, 54], [21, 54]]
我怎样才能做到这一点?我们可以假设坐标中的“间隙”总是连续的或为零,就像坐标中的最后两个“元组”一样。我们在这里也只处理整数。我已经设法编写了一个函数,可以对 1 个 y 坐标执行此操作:
def fillElements(sequence):
k=0
while (sequence[k][0]+1) == (sequence[(k+1) % len(sequence)][0]):
k+=1
if k == len(sequence):
return sequence
else:
dummy = list(range((sequence[k][0]+1), sequence[k+1][0]))
for l in range(len(dummy)):
sequence.append([dummy[l], sequence[0][1]])
return sequence
这个函数首先通过比较当前元素的x值和下一个元素的x值来找到坐标缺失的“断点”;如果它们相距超过 1,则存在中断。我还处理了一些边缘情况,其中 (i+1) 超出了列表的长度;相反,它会返回并与第一个条目进行比较。在这种情况下,当 while 循环结束时,运行索引 k 应该正好是序列的长度,并且序列原封不动地返回。如果运行索引小于序列的长度,则表示存在中断。在这种情况下,我使用 range() 创建了一个虚拟列表,其中包含所有缺失的 x 值,边界是第 k 个“元组”,其中循环被破坏,+1 因为我不想拥有两次相同的 x 值,以及下一个元素。
然而,虽然这个函数有效,但代码有点难看,就像我说的,它只适用于一个 y 坐标。解决后者是最重要的部分,但如果有人建议改进此代码或首先使用其他方法,请告诉我。结果列表中坐标的顺序并不重要。
e:如果是“唯一的 y 坐标”,例如“元组”[20, 51],则不应更改任何内容,因为“中间”没有元素。
解决方案
如果我理解正确,您想填补坐标中的空白x
,每次y
坐标更改时都会重置。
以下是一个 Python 3 解决方案,它将做到这一点:
def fill_gaps(coordinates):
last_x, last_y = None, None
for x, y in coordinates:
if y == last_y:
# Fill in any potential gaps between the last value and us
yield from ([new_x, y] for new_x in range(last_x + 1, x))
last_x, last_y = x, y
yield [x, y]
This uses a generator to make the code a bit easier, so if you want a list you will need to wrap the call with list()
to make that happen:
result = list(fill_gaps(coords))
This solution requires the co-ordinates to be sorted as you stated.
推荐阅读
- sql-server - TSQL 将行分隔为后续操作行
- python-3.x - 如何使用python脚本在主动打开的浏览器中查找选项卡名称列表
- javascript - 占位符图像没有正确加载卡片 [ReactJs]
- javascript - 如何限制分页中显示的页面数量
- c# - 如果不在构造函数中,如何验证数据?
- node.js - API 发布 x-www-form-urlencoded 数据但在 json 上失败
- xml - XSLT 通用将结构值类型转换为单值字符串
- c# - 如何使用 sizeof 保留易重构?
- javascript - 如何更改具有相同值而没有突变的对象的键值,同时在 javascript 中保持对未更改键的引用相同?
- vue.js - VueJs - 避免无用的 v-for 迭代