【问题标题】:combine two loops in python在python中组合两个循环
【发布时间】:2013-03-06 18:02:15
【问题描述】:

假设有两个多边形 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), 其中 poly 是包含多边形顶点坐标的对 (x,y) 列表。该算法称为“光线投射法”

我希望以一种优雅的方式(保存行编码)将两个循环合二为一。

【问题讨论】:

  • 因为我认为你的工作是相关的,所以看看 numpy,它内置了对向量和矩阵的支持。你可以在那里做一些很好的技巧(比如向量化循环),这些技巧完全是用 C 语言编写的,而且速度非常快。它不仅是为了速度:还有大量内置的数学方法可以让你更轻松地解决这些问题。 scipy.org/Tentative_NumPy_Tutorial

标签: python optimization coding-style


【解决方案1】:

以下应该有效:

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

【讨论】:

    【解决方案2】:
    degree_of_contact = sum(point_inside_polygon(x, y, i) for i, j in ((p1, p2), (p2, p1)) for x, y in j)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    相关资源
    最近更新 更多