python 迭代器

Posted on 2019-09-05 14:10  S-skill  阅读(209)  评论(0)    收藏  举报

1. 迭代器
  可迭代对象(Iterable):内部包含__iter__()
  迭代器(Iterator): 内部含有__iter__(), __next__()
  str, list, dict, tuple, set,range,f,

2. 迭代器的特点:
  1. 节省内存
  2. 惰性机制
  3. 只能向前

 

1. dir的作用

# 所有的以上数据类型中都有一个函数__iter__(), 所有包含了__iter__()的数据类型都是可迭代的数据类型 Iterable(可迭代的东西)
# dir()来查看一个对象,数据类型中包含了那些东西


lst = [1,2,3]       # list
print(dir(lst))    # 查看有哪些数据类型
print("__iter__" in dir(lst))    # True(判断是可迭代的)
print("__next__" in dir(lst))          # False(判断不是迭代器)

# dir 判断 __iter__ 是否在dir查看的数据里面,如果有说明是可迭代的对象,会返回True

 

 

2. 迭代器的用法

# list是一个Iterable, 可迭代的
lst = ["炎龙侠", "风鹰侠", "雪獒侠", "黑犀侠", "地虎侠"]
# 获取迭代器
it = lst.__iter__()     # it是迭代器
# 迭代器往外拿元素.   __next__()
print(it.__next__())        # 炎龙侠
print(it.__next__())        # 风鹰侠
print(it.__next__())        # 雪獒侠
print(it.__next__())        # 黑犀侠
print(it.__next__())        # 地虎侠
print(it.__next__())        # 迭代到最后一个元素之后, 在进行迭代就报错了.

lst = ["炎龙侠", "风鹰侠", "雪獒侠", "黑犀侠", "地虎侠"]
# 模拟for循环
it = lst.__iter__()
while True:
    try:
        name = it.__next__()
        print(name)
    except StopIteration:   # 拿完了
        break

lst = [1,2,3]
print("__iter__" in dir(lst))       # 确定lst是一个可迭代的
print("__next__" in dir(lst))       # 确定lst不是一个迭代器

 

 

 3. 判断可迭代的和迭代器的其他用法

from  collections.abc  import  Iterable        # 可迭代的
from  collections.abc  import  Iterator        # 迭代器

lst = [1,2,3]
# isinstance(对象, 类型)  判断xxx对象是否是xxx类型
print(isinstance(lst, Iterable))    # True 判断是可迭代的
print(isinstance(lst, Iterator))    # False 判断不是迭代器

it = lst.__iter__()     #  it是迭代器
print(isinstance(it, Iterable))     # True 判断是否是可迭代的, 迭代器一定是可迭代的
print(isinstance(it, Iterator))     # True 迭代器里面一定有__next__(),__iter__()

f = open("demo", mode="r", encoding="utf-8")
print(isinstance(f, Iterable))      # True 判断f是可迭代的
print(isinstance(f, Iterator))      # True 判断f是迭代器

print("__next__" in dir(f))     # 判断f是迭代器
print(dir(f))

 

 

 

 

 

 

 

 

 

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3