在Python中合并两个循环

0 投票
2 回答
2120 浏览
提问于 2025-04-17 18:09

假设我们有两个多边形 p1 和 p2,其中 p2 完全在 p1 里面。

p1 = [(0, 10), (10, 10), (10, 0), (0, 0)]
p2 = [(2, 6), (6, 6), (6, 2), (2, 2)]

degree_of_contact = 0

xyarrays = [p1,p2]
p1_degree_of_contact = 0
for x,y in xyarrays[0]:
        if point_inside_polygon(x,y,xyarrays[1]):
            p1_degree_of_contact += 1

p2_degree_of_contact = 0
for x,y in xyarrays[1]:
        if point_inside_polygon(x,y,xyarrays[0]):
            p2_degree_of_contact += 1

degree_of_contact = p1_degree_of_contact + p2_degree_of_contact

这里的 point_inside_polygon 是用来判断一个点是否在多边形内部的(如果在里面返回 True,否则返回 False)。这个多边形的顶点坐标是以 (x,y) 的形式存储在一个列表中。这个算法叫做“射线法”。

我希望能以一种优雅的方式把两个循环合并成一个,以节省代码行数。

2 个回答

1
degree_of_contact = sum(point_inside_polygon(x, y, i) for i, j in ((p1, p2), (p2, p1)) for x, y in j)

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。

3

下面的代码应该可以正常运行:

degree_of_contact = 0
for tmp1, tmp2 in [(p1, p2), (p2, p1)]:
    for x,y in tmp1:
        if point_inside_polygon(x, y, tmp2):
            degree_of_contact += 1

撰写回答