之前已经讲过for循环语句了,今天我们就来看看怎样在for循环中建立动态范围吧。
我正在遍历列表,可以在迭代期间将元素添加到此列表中。所以问题是循环只迭代这个列表的原始长度。
代码:
i = 1 for p in srcPts[1:]: # skip the first item. pt1 = srcPts[i - 1]["Point"] pt2 = p["Point"] d = MathUtils.distance(pt1, pt2) if (D + d) >= I: qx = pt1.X + ((I - D) / d) * (pt2.X - pt1.X) qy = pt1.Y + ((I - D) / d) * (pt2.Y - pt1.Y) q = Point(float(qx), float(qy)) # Append new point q. dstPts.append(q) # Insert 'q' at position i in points s.t. 'q' will be the next i. srcPts.insert(i, {"Point": q}) D = 0.0 else: D += d i += 1
我已尝试在范围内使用for i(1,len(srcPts)):但是,即使将更多项目添加到列表中,范围也会保持不变。
问题是当你将它作为参数传递给范围生成器时,len(srcPts)只计算一次。因此,您需要有一个终止条件,在每次迭代期间重复计算srcPts的当前长度。有很多方法可以做到这一点,例如:
while i < len(srcPts): ....
以上就是python中for循环建立动态范围的方法。更多Python学习推荐:。
Copyright © 2019- hids.cn 版权所有 赣ICP备2024042780号-1
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务