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

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

问题描述

我想知道对for循环中最后一个元素进行特殊处理的最好方法(更紧凑和pythonic方式)。有一段代码只能在元素之间调用元素,在最后一个元素中被抑制。

这是我目前做的:

  for i,enumerate(data_list)中的数据:
code_that_is_done_for_every_element
if i!= len( data_list) - 1:
code_that_is_done_between_elements

有什么更好的办法吗? b
$ b

注意:我不想使用 reduce ;}


<解决方案大多数情况下,使得第一个迭代更为简单(而且更便宜),而不是最后一个迭代。
对于data_list中的数据,

  first = True 

如果是第一个:
first = False





$ b $ p $ >这将适用于任何迭代,即使是那些没有 len()



<









$ file $没有办法告诉这是否是最后一行!

除此之外,我不认为有一个通用的解决方案,因为它取决于你正在尝试做。例如,如果从列表中构建一个字符串,那么使用 str.join()比使用更好


使用相同的原则,但更紧凑:

  for i,line in enumerate(data_list):
if i> 0:
between_items()
item()

它呢? :)




对于@ofko以及其他真正需要查找迭代器的当前值是否小于$

 是最后一个,你需要向前看:

def lookahead(iterable):
传递给定迭代中的所有值,如果在当前值
(True)之后还有更多值,则增加
信息,或者如果它是最后一个值(假)。

#获取一个迭代器并且拉第一个值。
it = iter(可迭代)
last = next(it)
#运行迭代器以耗尽(从第二个值开始)。
for val:
#报告*前一个*值(来的更多)。
收益率最后一笔,真实
上一笔= val
#报告上一个值。
yield last,False

然后您可以像这样使用它:

 >>> (i,has_more)
0真
1真
2假


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

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

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