Python区分容器和迭代器

建议阅读:Python可迭代对象、迭代器和生成器的区别

容器

组织元素的数据结构,例如Python内置有list,set,dict,tuple

迭代器

定义了__next__()的对象,可以调用next()返回下一条数据

区分代码

调用iter(a) if iter(a),True则为迭代器

a = []  # 容器
print(iter(a) is iter(a))  # False
a = iter(a)  # 转换成迭代器
print(iter(a) is iter(a))  # True


class A:
    def __iter__(self):
        for _ in range(10000):
            yield 1


a = A()
print(iter(a) is iter(a))  # False
a = iter(a)  # 转换成迭代器
print(iter(a) is iter(a))  # True

或使用内置库

from typing import Iterator


class A:
    '''生成器'''
    def __iter__(self):
        yield 1


print(isinstance(A(), Iterator))
print(isinstance(iter(A()), Iterator)) # 生成器转迭代器
# False
# True

参考文献

  1. Effective Python
  2. python:容器、迭代器、生成器
  3. typing — 类型标注支持

你可能感兴趣的:(Python)