我想更多地使用循環迭代器,因爲我聽說它比索引循環更快。我不確定的一件事是如何很好地處理序列的結尾。我能想到的方式是使用try
和except StopIteration
,這對我來說看起來很醜。如何優雅地使用Python迭代器
更具體地說,假設我們被要求打印兩個排序列表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
你會怎麼編碼使它更整潔?
b是什麼意思? – detly 2010-12-10 09:08:40
該代碼幾乎難以辨認。描述它應該做什麼。 – 2010-12-10 09:09:53
a和b是兩個排序列表。任務是以非遞減的順序打印這兩個列表的元素 – nos 2010-12-10 09:25:34