为什么for循环中的值没有变化?

时间:2015-07-09 11:02:16

标签: python

为什么修改range(len(whole)/2)whole的值不会改变?你在for循环中称之为range(len...)的值是什么?

whole = 'selenium'
for i in range(len(whole)/2):
    print whole
    whole = whole[1:-1]

输出:

selenium
eleniu
leni
en

2 个答案:

答案 0 :(得分:8)

range()生成一次的整数列表。然后该列表由for循环迭代。每次迭代都不会重新创建;那效率很低。

您可以改为使用while循环:

i = 0
while i < (len(whole) / 2):
    print whole
    whole = whole[1:-1]
    i += 1

每次循环迭代都会重新测试while条件。

答案 1 :(得分:3)

范围功能创建一个列表

[0, 1, 2, 3]

for循环遍历列表的值。

每次都不会重新创建列表

但在正常列表中并非如此

wq=[1,2,3]

for i in wq:
    if 3 in wq:
        wq.remove(3)
    print i

1
2