【问题标题】:python shorten multiple nested loops in Grasshopperpython缩短Grasshopper中的多个嵌套循环
【发布时间】:2016-04-30 22:59:17
【问题描述】:

如果不使用多个嵌套循环,我还没有找到解决此问题的方法。问题是我正在使用 Rhinoceros 的几何方法对两个列表进行比较。基本上有一个行列表,一组起点和终点(嵌套列表)。所有的起点和终点都接触线。该脚本将最接近开头的行的索引与最接近结尾的行的索引进行比较,如果它们匹配,则返回True

这是我当前的代码:

for i in range (10):
    for j in range (100):
        for k in range (3):
            for l in range (len(linesList)):
                pullSt = rc.Geometry.Curve.ClosestPoint(linesList[l], stPoint[i][j][k], 0.0001)[0]
                pullEnd = rc.Geometry.Curve.ClosestPoint(linesList[l], endPoint[i][j][k], 0.0001)[0]
                if pullSt == True and pullEnd == True:
                    match[i][j][k] = True

我认为它可能与生成器表达式一起使用,但我被卡住了,因为似乎我实际上必须在相互比较之前临时存储 pullSt 和 pullEnd 值。我知道我可能会超载我的记忆,必须有更快的方法来做到这一点,但我不确定如何。

注意:如果直线和点之间的距离小于 0.0001 的容差,则 rc.Geometry.Curve.ClosestPoint 返回True,表示点在直线上。

【问题讨论】:

  • 您只是希望有更少的嵌套循环吗?有 itertools.product 会给你一个等效的迭代器 itertools.product(range(10),range(100), range(3))
  • 我认为 itertools 产品或生成器函数可能会起作用,但我不知道如何将脚本的重要部分集成到其中。关于 pullSt、pullEnd 等的一点。
  • 你会保持不变。 for i, j, k in itertools.product(...) 然后是循环的最里面部分。我理解你在问什么吗?您正在做的一件无关紧要的事情是在找到您需要的线路后继续检查线路。我可能会使用 itertools 折叠前三个循环,然后保留内部循环,这样当你找到正确的行时,你可以打破它。 pullStpullEnd 的内存可以忽略不计。您只需将它们保留一次迭代。

标签: python iterator generator grasshopper rhino3d


【解决方案1】:

这种循环似乎没有引用您数据集中的任何其他内容,因此,使用 Grasshopper 自己的内置工具处理每个对象的代码要短得多。

pullSt = rc.Geometry.Curve.ClosestPoint(linesList[l], stPoint, 0.0001)[0]
pullEnd = rc.Geometry.Curve.ClosestPoint(linesList[l], endPoint, 0.0001)[0]
if pullSt == True and pullEnd == True:
    match = True

如果您右键单击输入,您可以将它们从树访问更改为项目访问。

这只是猜测,因为您还没有说出您实际要解决的问题。

如果您发布问题,我会更新答案以更具体。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-15
    • 2023-03-15
    • 2022-11-01
    • 2019-04-21
    • 2017-03-01
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    相关资源
    最近更新 更多