粗糙学习-py

iterator与generator

2019-06-14  本文已影响0人  Darui30

可迭代对象:

迭代器:

#coding:utf8

class BookCollection(object):
    def __init__(self):
        self.data = ['《往事》','《只能》','《回味》']
        self.index = 0
        pass
    def __iter__(self):
        return self
    def __next__(self):
        if self.index >= len(self.data):
            raise StopIteration()
        r = self.data[self.index]
        self.index += 1
        return r
        

books = BookCollection()
for book in books:
    print(book) # 《往事》
                # 《只能》
                # 《回味》

生成器

#coding:utf8

# 这个只是一个列表
n = [i for i in range(1,11)]
print(n) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(type(n)) # <class 'list'>

print('=='*20) # ========================================

# 变成小括号,则变成生成器
n = (i for i in range(1,11))
print(n)    # <generator object <genexpr> at 0x107e982b0>
print(type(n)) # <class 'generator'>
print(next(n)) # 1
print(next(n)) # 2
print(next(n)) # 3
print(next(n)) # 4
print(next(n)) # 5

print('=='*20) # ========================================

for i in n:print(i) # 6
                    # 7
                    # 8
                    # 9
                    # 10


print('=='*20) # ========================================


# 函数举例子
def gen0(max):
    n = 0
    while n<=max:
        n+=1
        print(n)
        
print(gen0(9))  # 1
                # 2
                # 3
                # 4
                # 5
                # 6
                # 7
                # 8
                # 9
                # 10
                # None



print('=='*20) # ========================================

# 不做打印,yield,生成器
def gen(max):
    n = 0
    while n<=max:
        n+=1
        yield n

print(gen(9))   # <generator object gen at 0x105bff308>
for i in gen(9):
    print(i)    # 1
                # 2
                # 3
                # 4
                # 5
                # 6
                # 7
                # 8
                # 9
                # 10
上一篇下一篇

猜你喜欢

热点阅读