Python collections 判断实例是否为可迭代对象或迭代器
【摘要】 环境信息ModelArtsNotebook - pytorch1.4-cuda10.1-cudnn7-ubuntu18.04JupyterLab - Notebook - Conda-python3 collections 判断实例是否为可迭代对象或迭代器from collections.abc import Iterable# 可迭代对象中需要实现 __iter__ 或者 __geti...
环境信息
- ModelArts
- Notebook - pytorch1.4-cuda10.1-cudnn7-ubuntu18.04
- JupyterLab - Notebook - Conda-python3
- Notebook - pytorch1.4-cuda10.1-cudnn7-ubuntu18.04
collections 判断实例是否为可迭代对象或迭代器
from collections.abc import Iterable
# 可迭代对象中需要实现 __iter__ 或者 __getitem__
# list() 是 可迭代对象吗?
isinstance(list(),Iterable)
True
from collections.abc import Iterator
# 迭代器 __iter__ __next__ stopiteration
# list()是迭代器吗?
isinstance(list(),Iterator)
False
# iter(list())是迭代器吗?
isinstance(iter(list()),Iterator)
True
help
help(iter)
Help on built-in function iter in module builtins:
iter(...)
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator
Get an iterator from an object. In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.
help(Iterator)
elp on class Iterator in module collections.abc:
class Iterator(Iterable)
| Method resolution order:
| Iterator
| Iterable
| builtins.object
|
| Methods defined here:
|
| __iter__(self)
|
| __next__(self)
| Return the next item from the iterator. When exhausted, raise StopIteration
......
help(Iterable)
Help on class Iterable in module collections.abc:
class Iterable(builtins.object)
| Methods defined here:
|
| __iter__(self)
......
相关链接
备注
- 欢迎各位同学一起来交流学习心得^_^
- 在线课程、沙箱实验、认证、论坛和直播,其中包含了许多优质的内容,推荐了解与学习。
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)