对于变长for-in的测试

def test_variable_forin():
    alist = ['a', 'bb', 'cc', 'dd']
    count = 0
    for i in alist:
        print i
        count += 1
        if len(i) > 1:
            alist.remove(i)
    print alist
    print count
        
test_variable_forin()

结果:

a
bb
dd
['a', 'cc']
3

分析与结论:

      期待结果count = 4, alist最后为['a'], 很显然与期待结果不同。

      原因是:python在for-in循环中会重新计算 iterable类型值,但计数器不会清零。

      第一次运行:i='a',alist 不变, count = 1

      第二次运行:i='bb',alist=['a', 'cc', 'dd'], count = 2

      第三次运行:i='dd',alist=['a', 'cc'], count = 3

      结论:不要在使用for-in循环时,改变其iterable类型的变量。

posted @ 2013-02-20 16:49  道以万计  阅读(172)  评论(0)    收藏  举报