为什么修改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
答案 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