如何优雅地使用Python迭代器
我尝试更多地使用迭代器进行循环,因为我听说它比索引循环更快。我不确定的一件事是如何很好地处理序列的结尾。我能想到的方法是使用 try
和 except StopIteration
,这对我来说看起来很难看。
更具体地说,假设我们被要求打印两个排序列表 a
和 b
的合并排序列表。我会写以下内容
aNull = False
I = iter(a)
try:
tmp = I.next()
except StopIteration:
aNull = True
for x in b:
if aNull:
print x
else:
if x < tmp:
print x
else:
print tmp,x
try:
tmp = I.next()
except StopIteration:
aNull = True
while not aNull:
print tmp
try:
tmp = I.next()
except StopIteration:
aNull = True
您将如何编码以使其更整洁?
I am trying to use iterators more for looping since I heard it is faster than index looping. One thing I am not sure is about how to treat the end of the sequence nicely. The way I can think of is to use try
and except StopIteration
, which looks ugly to me.
To be more concrete, suppose we are asked to print the merged sorted list of two sorted lists a
and b
. I would write the following
aNull = False
I = iter(a)
try:
tmp = I.next()
except StopIteration:
aNull = True
for x in b:
if aNull:
print x
else:
if x < tmp:
print x
else:
print tmp,x
try:
tmp = I.next()
except StopIteration:
aNull = True
while not aNull:
print tmp
try:
tmp = I.next()
except StopIteration:
aNull = True
How would you code it to make it neater?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为更对称地处理
a
和b
会让它更容易阅读。此外,在 Python 2.6 中使用带有默认值的内置next
函数可以避免处理StopIteration
的需要:以下函数概括了适用于任意多个迭代器的方法。
I think handling
a
andb
more symmetrically would make it easier to read. Also, using the built-innext
function in Python 2.6 with a default value avoids the need to handleStopIteration
:The following function generalizes the approach to work for arbitrarily many iterators.
您错过了迭代器的全部要点。您无需手动调用
I.next()
,只需迭代I
。已编辑
要合并两个迭代器,请使用
itertools
模块中非常方便的函数。您想要的可能是izip
:再次编辑
正如评论中所指出的,这实际上不起作用,因为列表 a 中可能有多个项目小于列表 b 中的下一个项目。但是,我意识到还有另一个内置函数可以处理此问题:
heapq.merge
。You're missing the whole point of iterators. You don't manually call
I.next()
, you just iterate throughI
.Edited
To merge two iterators, use the very handy functions in the
itertools
module. The one you want is probablyizip
:Edit again
As pointed out in the comments, this won't actually work, because there could be multiple items from list a smaller than the next item in list b. However, I realised that there is another built-in funciton that deals with this:
heapq.merge
.函数
sorted
适用于列表和迭代器。也许这不是您想要的,但下面的代码可以工作。The function
sorted
works with lists and iterators. Maybe it is not what you desire, but the following code works.