【发布时间】:2011-05-23 08:55:09
【问题描述】:
我正在尝试更多地使用迭代器进行循环,因为我听说它比索引循环更快。我不确定的一件事是如何很好地处理序列的结尾。我能想到的方法是使用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
你会如何编码让它更整洁?
【问题讨论】:
-
该代码几乎难以辨认。描述它应该做什么。
-
a 和 b 是两个排序列表。任务是以非递减顺序打印这两个列表的元素
-
所以你需要合并两个排序的列表。