在"for"循环中检测最后一个元素的pythonic方法是什么? [英] What is the pythonic way to detect the last element in a 'for' loop?

查看:69
本文介绍了在"for"循环中检测最后一个元素的pythonic方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道对for循环中的最后一个元素进行特殊处理的最佳方法(更紧凑和"pythonic"的方法).有一段代码只应在元素之间调用,而在最后一个元素中将其隐藏.

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?

注意:我不想通过使用reduce之类的技巧来做到这一点. ;)

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

推荐答案

在大多数情况下,使 first 迭代成为特例而不是最后一个迭代更容易(也更便宜):

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()

这将适用于任何可迭代的对象,即使对于没有len()的对象也是如此:

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!

除此以外,我认为没有普遍上乘的解决方案,因为这取决于您要执行的操作.例如,如果要从列表中构建字符串,那么使用str.join()自然比使用具有特殊情况"的for循环自然要好.

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? :)

对于@ofko,以及其他确实需要找出没有len()的可迭代对象的当前值是否为最后一个值的其他人,您需要向前看:

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

这篇关于在"for"循环中检测最后一个元素的pythonic方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆