当每隔一列少一个元素时,如何将数组列表组织成锯齿形

问题描述 投票:0回答:1

我正在制作一个关于包装圆的程序,即使它们是六边形包装的,我也需要它们之间有一条锯齿形路径。这意味着有时每隔一列就会少一个元素。下面是未实现锯齿形路径时的路径外观的图片:

这就是我的尝试。对于前三行,它可以正常工作,但由于某种原因,此后它开始变得混乱。

这是我的代码:

def zigzag_positions(cols, rows, stored_seed_positions, y_diff):
zigzag_positions = []
s = 0


for i in range(int(cols)):
    if i % 2 == 0:  # even cols
        for j in range(0 - s, int(rows), 1):
            index = i * int(rows) + j
            if index < len(stored_seed_positions):
                zigzag_positions.append(stored_seed_positions[index])
    else:  # odd cols
        for j in range(int(rows)-2, -1, -1):
            index = i * int(rows) + j
            if index < len(stored_seed_positions):
                zigzag_positions.append(stored_seed_positions[index])

        s += 1


return zigzag_positions

所以基本上具有相同 x 值的所有其他坐标集都需要以某种方式进行切换。我该怎么做?这是正常路径的示例数组:

[(102, 102), (102, 206), (102, 310), (102, 414), (102, 518), 
(193, 154), (193, 258), (193, 362), (193, 466), 
(285, 102), (285, 206), (285, 310), (285, 414), (285, 518), 
(376, 154), (376, 258), (376, 362), (376, 466), 
(468, 102), (468, 206), (468, 310), (468, 414), (468, 518), 
(559, 154), (559, 258), (559, 362), (559, 466)]

这是我想要的数组:

[(102, 102), (102, 206), (102, 310), (102, 414), (102, 518), 
(193, 466), (193, 154), (193, 258), (193, 362),
(285, 102), (285, 206), (285, 310), (285, 414), (285, 518), 
(376, 466), (376, 362), (376, 258), (376, 154),
(468, 102), (468, 206), (468, 310), (468, 414), (468, 518), 
(559, 466), (559, 362), (559, 258), (559, 154)]
python arrays list
1个回答
0
投票

IIUC,你想要一个 交替

sorted
:

from itertools import groupby, chain

out = list(
    chain.from_iterable(
        sorted(g, reverse=not i % 2)
        for i, (_, g) in enumerate(groupby(sorted(data), lambda t: t[0]))
    )
)

输出(用 matplotlib/shapely 制作):

使用的输入:

# doesn't need to be sorted in any way

data = [
    (102, 102), (102, 206), (102, 310), (102, 414), (102, 518), 
    (193, 154), (193, 258), (193, 362), (193, 466), 
    (285, 102), (285, 206), (285, 310), (285, 414), (285, 518), 
    (376, 154), (376, 258), (376, 362), (376, 466), 
    (468, 102), (468, 206), (468, 310), (468, 414), (468, 518), 
    (559, 154), (559, 258), (559, 362), (559, 466)
]
© www.soinside.com 2019 - 2024. All rights reserved.