大多數時候更容易(便宜),使第一迭代的特殊情況,而不是的最後一個:
first = True
for data in data_list:
if first:
first = False
else:
between_items()
item()
這將爲可迭代的工作,甚至對那些沒有len()
:
file = open('/path/to/file')
for line in file:
process_line(line)
# No way of telling if this is the last line!
除此之外,我不認爲有一個通用的解決方案,因爲它取決於你正在嘗試做什麼。例如,如果要從列表中構建一個字符串,那麼使用str.join()
比使用for
「特殊情況」循環更好。
使用相同的原則,但更緊湊:
for i, line in enumerate(data_list):
if i > 0:
between_items()
item()
看起來很熟悉,不是嗎? :)
對於@ofko,和其他人誰真的需要找出是否可迭代的不len()
電流值是最後一個,你需要向前看:
def lookahead(iterable):
"""Pass through all values from the given iterable, augmented by the
information if there are more values to come after the current one
(True), or if it is the last value (False).
"""
# Get an iterator and pull the first value.
it = iter(iterable)
last = next(it)
# Run the iterator to exhaustion (starting from the second value).
for val in it:
# Report the *previous* value (more to come).
yield last, True
last = val
# Report the last value.
yield last, False
然後你可以使用它像這樣:
>>> for i, has_more in lookahead(range(3)):
... print(i, has_more)
0 True
1 True
2 False
那他第一次呢?它是否也應該被壓制? – 2009-10-27 12:04:29
你能告訴我們元素之間做了什麼嗎? – SilentGhost 2009-10-27 12:08:59
我希望得到一個通用案例的答案,但是我需要的一個具體案例是將一些東西寫入流中,並在它們之間使用分隔符,就像stream.write(','.join(name_list)) ,但在一個for循環而不是連接字符串,因爲有很多寫道... – 2009-10-27 12:32:48