python获取循环最后一个值_什么是Pythonic的方式来检测python'for'循环中的最后一个元素?...

博客探讨了如何更优雅地处理Python for循环中最后一个元素的特殊情况。通常,将首次迭代作为特殊情况处理比处理最后一次迭代更为简便。文中提供了一种方法,通过设置一个`first`标志并在循环中检查它来实现这一目标。此外,还讨论了在没有`len()`的情况下判断是否为最后一个元素的技巧,并给出了一种使用`lookahead`函数的解决方案。
摘要由CSDN通过智能技术生成

I'd like to know the best way (more compact and "pythonic" way) to do a special treatment for the last element in a for loop. There is a piece of code that should be called only between elements, being suppressed in the last one.

Here is how I currently do it:

for i, data in enumerate(data_list):

code_that_is_done_for_every_element

if i != len(data_list) - 1:

code_that_is_done_between_elements

Is there any better way?

Note: I don't want to make it with hacks such as using reduce ;)

解决方案

Most of the times it is easier (and cheaper) to make the first iteration the special case instead of the last one:

first = True

for data in data_list:

if first:

first = False

else:

between_items()

item()

This will work for any iterable, even for those that have no len():

file = open('/path/to/file')

for line in file:

process_line(line)

# No way of telling if this is the last line!

Apart from that, I don't think there is a generally superior solution as it depends on what you are trying to do. For example, if you are building a string from a list, it's naturally better to use str.join() than using a for loop “with special case”.

Using the same principle but more compact:

for i, line in enumerate(data_list):

if i > 0:

between_items()

item()

Looks familiar, doesn't it? :)

For @ofko, and others who really need to find out if the current value of an iterable without len() is the last one, you will need to look ahead:

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

Then you can use it like this:

>>> for i, has_more in lookahead(range(3)):

... print(i, has_more)

0 True

1 True

2 False

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值