大多数情况下,将第一次迭代设为特殊情况而不是最后一次更容易(也更便宜):
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)
除此之外,我认为没有一种普遍优越的解决方案,这取决于你要做什么。例如,如果你正在从列表构建一个字符串,自然而然地使用 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).
"""
it = iter(iterable)
last = next(it)
for val in it:
yield last, True
last = val
yield last, False
然后你可以像这样使用它:
>>> for i, has_more in lookahead(range(3)):
... print(i, has_more)
0 True
1 True
2 False