有多个迭代器类,具体取决于您要迭代的内容:
>>> import re
>>> re.finditer("\d+", "1 ha 2 bah").__class__
<type 'callable-iterator'>
>>> iter([1, 2]).__class__
<type 'listiterator'>
>>> iter("hurm").__class__
<type 'iterator'>
两个问题:
- 它们之间有什么有意义的区别吗?
- 为什么第一个叫做
callable-iterator
?你绝对不能调用它。
最佳答案
BrenBarn非常愉快地回答了#1,但我相信我已经解开了#2 的谜团。也就是说,callable-iterator
是使用 iter
的第二种形式返回的:
>>> help(iter)
iter(...)
iter(collection) -> 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.
即:
>>> def globals_are_bad_mmkay():
global foo
foo += 1
return foo
>>> foo = 0
>>> it = iter(globals_are_bad_mmkay, 10)
>>> it
<callable-iterator object at 0x021609B0>
>>> list(it)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
关于python - 可调用迭代器和列表迭代器和迭代器之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19287066/