python 中的for循环如何修改循环变量?
PHP中文网
PHP中文网 2017-04-17 11:10:05
0
7
1322

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

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(7)
阿神

Modify the for statement to use a loop statement.

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

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

大家讲道理

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.

刘奇

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.

大家讲道理

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.

洪涛

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).

左手右手慢动作

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template