for 之 循环引发异常

来源:互联网 发布:淘宝怎么参与团购 编辑:程序博客网 时间:2024/04/29 09:03

在python中如果在for中引用一个函数被告知寻展开一个元素,比如一个数字,这种情况会引发TypeError的异常。

例如:

#!/usr/bin/env python

def test(lst):
        print 'test'
        for sublist in lst:
                print sublist

test(1)

#############################

运行结果:

test
Traceback (most recent call last):
  File "test_yield.py", line 12, in <module>
    test(1)
  File "test_yield.py", line 5, in test
    for sublist in lst:
TypeError: 'int' object is not iterable

再看:

#/usr/bin/env python
def test(lst):
        print 'test'
        for sublist in lst:
                print sublist

test([1])
################################

运行结果:

test
1
看明白了吗?如果值数字就会产生异常,如果是列表就可以。因为数字是“int”型不可迭代的而列表是“口以”的。

原创粉丝点击