列表生成式、生成器

"""
列表生成式
"""
list1 = [x * x for x in range(10) if x % 2 == 0]
list2 = [x if x >= 0 else -x for x in [0, -1, -3, 6, -19]]
list3 = [x + y for x, y in [(1, 1), (2, 2)]]
list4 = [m+n for m in 'abc' for n in '123']
print(list1)
print(list2)
print(list3)
print(list4)
"""
生成器
"""
g = (x for x in range(10))
for x in g:
    print(x)


def fib(max):
    a, b, n = 0, 1, 0
    while n < max:
        yield b
        a, b = b, a+b
        n += 1


if __name__ == '__main__':
    gg = fib(10)
    print('==================')
    for x in gg:
        print(x)

 

posted @ 2020-02-05 14:32  Tarzen  阅读(115)  评论(0编辑  收藏  举报