• 技术文章 >Python技术 >Python基础教程

    Python中for循环的动态范围

    2020-11-04 15:55:06原创2777

    之前已经讲过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学习网教学中心

    专题推荐:for循环的动态范围;python
    上一篇:如何使用Python discard() 方法?怎么用? 下一篇:Python函数嵌套变量的使用方法

    相关文章推荐

    • python中for循环的底层实现• Python for循环及用法详解• python中的for循环语句怎么写• python如何写for循环• python的for循环如何实现• 如何使python for循环不停止• 工作繁琐?试试Python循环语句(for循环篇)• Python中for循环语句和while循环语句有何不同• PyThon range()函数中for循环用法

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网