迭代字符串

时间:2014-05-28 13:38:41

标签: python iterator

我还在学习,所以要温柔。

给出以下代码。

str = "sometext"
it = iter(str)
print it
print len(list(it))
print len(list(it))

我得到以下输出。

<iterator object at 0x1070b9990>
8
0

为什么对象的内容只能使用一次?

2 个答案:

答案 0 :(得分:5)

迭代器是如何工作的:一旦你对某些元素进行迭代,除了创建一个新的迭代器并重新开始之外,不会再回头了。

答案 1 :(得分:2)

Iterator仅供一次性使用(或更好的&#34;消费内容一次&#34;)并完成:

>>> text = "sometext"
>>> it = iter(text)
>>> it
<iterator at 0x7f7ea01aead0>
>>> lst = list(it)
>>> lst
['s', 'o', 'm', 'e', 't', 'e', 'x', 't']

list已遍历所有内容并完成。

再次尝试使用迭代器:

>>> it.next()
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-18-54f0920595b2> in <module>()
----> 1 it.next()

导致StopIteration例外。

接下来,你必须再次创建迭代器:

>>> it = iter(text)

并使用它。事实上,迭代意味着在其上调用next()(这是list在内部所做的事情):

>>> it.next()
's'
>>> it.next()
'o'
>>> it.next()
'm'
>>> it.next()
'e'
>>> it.next()
't'
>>> it.next()
'e'
>>> it.next()
'x'
>>> it.next()
't'
>>> it.next()
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-18-54f0920595b2> in <module>()
----> 1 it.next()

请注意,list次迭代(和for循环)会捕获StopIteration异常并且不会将其传播出去,因为它只是&#34;没有更多项目可以获取& #34;

你想下次尝试吗?获得新鲜的迭代器。这个用尽了。

相关问题