每天CookBook之Python-059

  • 使用生成器创建新迭代器

def frange(start, stop, increment):
    x = start
    while x < stop:
        yield x
        x += increment


for n in frange(0, 4, 0.5):
    print(n)

print(list(frange(0, 1, 0.125)))


def countdown(n):
    print('Starting to count from', n)
    while n > 0:
        yield n
        n -= 1
    print('Done!')


c = countdown(3)

print(c)

print(next(c))
print(next(c))
print(next(c))
print(next(c))

out

0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
[0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
<generator object countdown at 0x00692870>
Starting to count from 3
3
2
1
Done!

Process finished with exit code 1

posted @ 2016-07-21 23:16  4Thing  阅读(89)  评论(0编辑  收藏  举报