python中loop是什么语句_for-loop – 什么是python的方式来检测python中的最后一个元素’for’循环?...

大多数时候,使第一次迭代更容易(和更便宜)是特殊情况而不是最后一次:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值