之前已经讲过for循环语句了,今天我们就来看看怎样在for循环中建立动态范围吧。
我正在遍历列表,可以在迭代期间将元素添加到此列表中。所以问题是循环只迭代这个列表的原始长度。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <p style= "line-height: 1.75em;" ><span style= "font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;" >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<br></span></p>
|
我已尝试在范围内使用for i(1,len(srcPts)):但是,即使将更多项目添加到列表中,范围也会保持不变。
问题是当你将它作为参数传递给范围生成器时,len(srcPts)只计算一次。因此,您需要有一个终止条件,在每次迭代期间重复计算srcPts的当前长度。有很多方法可以做到这一点,例如:
1 2 3 4 | <p style= "line-height: 1.75em;" ><span style= "font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;" > while i < len(srcPts):
....<br></span></p>
|
以上就是python中for循环建立动态范围的方法。更多Python学习推荐:PyThon学习网教学中心。