search

Home  >  Q&A  >  body text

python 中的for循环如何修改循环变量?

如题.想用python来做个最长连续递增子序列的函数,但发现在用for i in range(0,len(seq))的时候,在循环体不能修改i的值,请问有什么方法可以修改?

PHP中文网PHP中文网2804 days ago1310

reply all(7)I'll reply

  • 阿神

    阿神2017-04-17 11:12:05

    Modify the for statement to use a loop statement.

    i = 0
    length = len(seq)
    while i < length:
        #just do it
        i += 1

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 11:12:05

    Why does the longest continuous increasing subsequence need to modify i

    for i in range(len(s1)):
      for j in range(len(s2)):
         if s1[i] == s2[j]:
            f[i][j] = f[i-1][j-1] + 1
         else:
            f[i][j] = max(f[i-1][j],f[i][j-1]);

    The code was written casually, it should be correct

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 11:12:05

    The reason why the python for loop cannot modify the loop variable is that range() is like an iterator. It will only output information and cannot modify the contents of the iterator. The C structure of python iterator is a pointer and a list of objects. Modifying the value of a loop object is a C way of thinking, and it is best not to use it when writing python code.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 11:12:05

    It is seriously not recommended to modify the iteration variable. In many cases, it is impossible to use it for random access. There are many other ways to do this. Using Python's for-comprehension and some reduce methods can solve it efficiently and stably.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 11:12:05

    You should use list parsing and other methods to make the required modifications in advance. List parsing performance is very good, and for is only used for other operations.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 11:12:05

    You can modify the value of i, but the for statement will reassign i after each loop. So the question you ask is not whether you can modify i, but the behavior of the iterator. The answer is no.
    You can use while, or use a generator:

    def incSeq(seq):
        start = 0
        for i in xrange(1, len(seq)):
            if seq[i] < seq[i-1]:
                yield start, i - start
                start = i
    maxIncSeq = reduce(lambda x,y: x if x[1]>y[1] else y, incSeq(seq))

    Get the longest increasing substring length and starting position, time complexity O(n).

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 11:12:05

    Why do you need to modify the value of the loop variable? Doing so may cause problems. It is recommended to use other methods to achieve this, such as the while loop mentioned by several people above.

    reply
    0
  • Cancelreply