我知道iterator
是iterable
,但只有一次通过。在
例如,itertools
中的许多函数都将iterable
作为参数,例如islice
。如果我看到api显示iterable
,我是否可以总是传入iterator
?在
正如@delnan指出的:
Although every
iterator
is aniterable
, some people (outside the core team) say "iterable" when they mean "something that can be iterated several times with with the same results". Some code in the wild claims to work oniterables
but actually doesn't work withiterators
.
这正是我所关心的。支持多路径的iterable
有名字吗?像C中的IEnumerable
?在
如果我要构建一个声称支持iterable
的函数,那么实际上也支持iterator
是最佳实践吗?在
您应该看看在the ^{} module 中定义的抽象基类。就您的目的而言,}可能是最有用的,因为它们分别需要},而这又需要一组定义良好的值,这些值可以重复迭代。在
Container
或{__contains__
和{是的,因为每个迭代器也是iterable。在
如果一个对象定义了
__iter__()
方法,那么它就是iterable。每个迭代器都有这个方法,它返回迭代器本身。在是的,itertools中的函数是为迭代器设计的。函数签名之所以说
iterable
,是因为它们还处理列表、元组和其他不是迭代器的iterable。在A sequence是一个iterable,它支持通过
__getitem__()
特殊方法使用整数索引进行有效的元素访问,并定义返回序列长度的len()
方法。在这个定义与不是迭代器的所有iterable的集合稍有不同。(您可以定义一个(残废的)自定义类,它有一个
__getitem__
,但没有__len__
。它将是一个iterable,它不是迭代器,但也不是sequence
。)但是
sequences
非常接近您要查找的内容,因为所有序列都是可重复多次的iterable。在内置到Python中的sequence types示例包括}。在
str
、unicode
、list
、tuple
、bytearray
、buffer
和{以下是从glossary中挑选的一些定义:
相关问题 更多 >
编程相关推荐