迭代器yield

我认为生成器是迭代器中的一种,属个人看法.
for, while, range, iter, enumerate属于迭代器, xrange 属于生成器,还包括这种形式: [i for i in range(4) if i > 2]

>>> it = iter(range(4))
>>> it.next()
>>> it.next()
0
>>> it.next()
1
>>> it.next()
2

带有 yield 的函数在 Python 中被称之为 generator(生成器),分享一个小程序

# -*- coding: utf-8 -*-


def para_list(data):
    if isinstance(data, list):
        for d in data:
            para_list(d)
    else:
        yield data


if __name__ == '__main__':
    all_data = list()
    a_list = [1,2,[3,4], [[5,6, [7,8]]], 9]
    for data in para_list(a_list):
        all_data.append(data)
    print all_data


# [1, 2, 3, 4, 5, 6, 7, 8, 9]

你可能感兴趣的:(yield,迭代器)