gpt4 book ai didi

python - 如何在元组列表中对相交的 Shapely 几何对象进行分组

转载 作者:太空狗 更新时间:2023-10-30 00:14:04 25 4
gpt4 key购买 nike

我有一个数据列表如下:

from shapely.geometry import box

data = [box(1,2,3,4), box(5,6,7,8), box(1,2,3,4)]
codes = ['A','B','C']

“数据”列表包含以下元素:

A = box(1,2,3,4)
B = box(5,6,7,8)
C = box(1,2,3,4)

我必须检查一个元素是否与任何其他元素相交。如果相交,则放在一个元组中;如果不相交,他们应该放在不同的元组中。预期结果是:

result = [(A,C), (B)]

怎么做?

我试过:

results = []
for p,c in zip(data,codes):
for x in data:
if p.intersects(x): ##.intersects return true if they overlap else false
results.append(c)
print results

最佳答案

保留映射到 A、B 和 C 的对象的字典,一组匹配的对象,如果它们不在我们的匹配集中,则在我们到达一个新字母后只添加没有匹配的单个元素作为所有可能的组合将进行测试:

from shapely.geometry import box
from itertools import combinations

codes = ["A", "B", "C"]
d = dict(zip(codes, data))
prev = codes[0]
matched, out = set(), []
for p1, p2 in combinations(codes, 2):
if d[p1].intersects(d[p2]):
out.append((p1, p2))
matched.update([p1, p2])
# when p1 is a new letter, we have tried all combs for that prev
# if prev is not in matched it did not intersect any other so
# add it as a single tuple and add to matched to avoid dupes
elif p1 != prev and prev not in matched:
out.append(tuple(prev,))
matched.add(prev)
prev = p1
# catch the last letter
if p2 not in matched:
out.append(tuple(p2,))
print(out)
[('A', 'C'), ('B',)]

关于python - 如何在元组列表中对相交的 Shapely 几何对象进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30834983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com