[英]Why doesn't the value in for loop change?
Why does the value of range(len(whole)/2)
not change after whole
is modified? 为什么
range(len(whole)/2)
的值在whole
修改后不会改变? And what do you call range(len...)
value in for-loop? 你在for循环中称为
range(len...)
值是什么?
whole = 'selenium'
for i in range(len(whole)/2):
print whole
whole = whole[1:-1]
output: 输出:
selenium
eleniu
leni
en
The range()
produces a list of integers once . 的
range()
产生一次整数列表。 That list is then iterated over by the for
loop. 该列表然后由
for
循环迭代。 It is not re-created each iteration; 每次迭代都不会重新创建; that'd be very inefficient.
那效率很低。
You could use a while
loop instead: 您可以使用
while
循环:
i = 0
while i < (len(whole) / 2):
print whole
whole = whole[1:-1]
i += 1
the while
condition is re-tested each loop iteration. while
循环迭代重新测试while
条件。
The range function creates a list 范围函数创建一个列表
[0, 1, 2, 3]
And the for loop iterates over the value of the list. 而for循环遍历列表的值。
The list is not recreated each and every time 该列表不会每次都重新创建
But this is not the case in normal list 但在正常列表中并非如此
wq=[1,2,3]
for i in wq:
if 3 in wq:
wq.remove(3)
print i
1
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.