簡體   English   中英

切片列表中的坐標列表

[英]List of coordinates into list of slices

像這樣轉換表示 (x, y) 坐標的元組列表的最有效方法是什么:

[(x1, y1), (x2, y2), ...]

到這樣的等效切片列表中:

[(slice_a_x, slice_a_y), (slice_b_x, slice_b_y), ...]?

例如 :

[(22, 9), (22, 10), (22, 11), (22, 12),
 (23, 9), (23, 10), (23, 11), (23, 12),
 (24, 9), (24, 10), (24, 11), (24, 12)]   

# would be [(slice(22, 25), slice(9, 13)), ]
[(22, 8), (22, 26), (23, 8), (23, 26), (24, 8), (24, 26)]  

# would be [(slice(22, 25), slice(8, 9)), (slice(22, 25), slice(26, 27)), ]
[(22, 8), (22, 26)]  

# would be [(slice(22, 23), slice(8, 9)), (slice(22, 23), slice(26, 27)), ]

編輯 :

根據 Jupri 的提議,另一個處理特定情況(間隙、漏洞、...)的版本:

import numpy as np
import more_itertools as mit

coordinates = np.array(coordinates)

# List of coordinates with y as interval
y_consec = [list(g) for g in mit.consecutive_groups(coordinates[:, 1])]
y_consec = [(min(g), max(g)) for g in y_consec for _ in range(len(g))]
y_coords = np.array(sorted(list(set(zip(*[y_consec, *coordinates[:, :-1].T])))), dtype=object)

# List of configurations following y
y_confs = sorted(list(set(c for c in y_coords[:, 0])))

# Split coordinates into homogeneous groups of y
y_groups = [[x for y, x in y_coords if y == c] for c in y_confs]

# Search consecutives x for each group
xyz = []
for y_conf, y_group in zip(y_confs, y_groups):
    x_consec = [(min(g), max(g)) for g in [list(group) for group in _mit.consecutive_groups(y_group)]]
    xyz.extend([(x, y_conf) for x in x_consec])

# Results
for s in xyz:
    print(s)
coordinates = [(22, 9), (22, 10), (22, 11), (22, 12),
 (23, 9), (23, 10), (23, 11), (23, 12),
 (24, 9), (24, 10), (24, 11), (24, 12)] 

您可以使用more_itertools.consecutive_groups

from more_itertools import consecutive_groups

# all x,y values unique and sorted

x = sorted(set([c[0] for c in coordinates]))
y = sorted(set([c[1] for c in coordinates]))

# consecutive groups, find max and min

gx = [[min(g),max(g)+1] for g in [list(group) for group in consecutive_groups(x)]]
gy = [[min(g),max(g)+1] for g in [list(group) for group in consecutive_groups(y)]]

# combine every min_x, max_x, with every min_y, max_y

results = [(mx[slice(2)], my[slice(2)]) for mx in gx for my in gy ]

print( results )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM