Python12:可迭代对象

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/plychoz/article/details/87869891

#可迭代对象:就是使用for循环遍历取值的对象就是可迭代对象
# for循环可以直接遍历:列表、元组、字符串、集合、range

from collections import Iterable

#判断对象是否是指定类型
result = isinstance('str', int)
print(result)

#元组
result = isinstance('(1,2)', Iterable)
print(result)

# 可迭代对象都有方法: __iter__
result = dir([1,2])
print(result)



# 迭代器
#在类里面有方法 __iter__ 和 __next__,创建的对象就是迭代器

from collections import Iterable
class MyIterable(object):
    def __init__(self):
        self.mylist = [4,5,9]
        self.current_index = 0
    def __iter__(self):
        # 返回一个迭代对象
        return self
    def __next__(self):
        if self.current_index < len(self.mylist):
            #获取迭代器的下一个值
            result = self.mylist[self.current_index]
            self.current_index +=1
            return result
        else:
            # 停止迭代,抛出异常
            raise StopIteration

# 创建迭代器
my_iterable = MyIterable()
result = isinstance(my_iterable, Iterable)
print(result)

#下面两段代码,只输出一遍结果
mm = next(my_iterable)
print(mm)
mm = next(my_iterable)
print(mm)
mm = next(my_iterable)
print(mm)
mm = next(my_iterable) #越界,抛出异常
print(mm)


for value in my_iterable:
    # for 循环里面直接停止迭代,系统内部帮助我们处理好了
    print(value)


'''
生成器
一个特殊的迭代器,同样可以通过next和for循环取值
值只能向后取,不能向前取
'''

# 列表生成式
result = [x for x in range(4)]
print(result, type(result))

#生成器
result = (x for x in range(4))
print(result, type(result))


# 下面两段代码只执行一个

value = next(result)
print(value)
value = next(result)
print(value)
value = next(result)
print(value)

for value in result:
    print(value)

#使用yield创建生成器
def show_num():
    for i in range(5):
        yield i
        #代码遇到yield会暂停,然后把结果返回过去
        #下次启动时,生成器会在暂停的位置
        #yield特点:可以返回多次值,return只能返回一个值

g = show_num()
print(g)

value = next(g)
print(value)
value = next(g)
print(value)
value = next(g)
print(value)

for value in g:
    print(value)

猜你喜欢

转载自blog.csdn.net/plychoz/article/details/87869891
今日推荐