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

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

问题描述

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

这是我目前的做法:

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

有没有更好的方法?

注意:我不想通过诸如使用 reduce 之类的技巧来实现它.;)

解决方案

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

first = True对于 data_list 中的数据:如果首先:第一个 = 错误别的:between_items()物品()

这适用于任何可迭代对象,即使是那些没有 len() 的对象:

file = open('/path/to/file')对于文件中的行:process_line(线)# 不知道这是否是最后一行!

除此之外,我认为没有普遍优越的解决方案,因为这取决于您要尝试做什么.例如,如果您要从列表构建字符串,那么使用 str.join() 自然比使用带有特殊情况"的 for 循环更好.><小时>

使用相同的原理但更紧凑:

for i, line in enumerate(data_list):如果我>0:between_items()物品()

看起来很眼熟是不是?:)

<小时>

对于@ofko 和其他真正需要找出不带 len() 的可迭代对象的当前值是否是最后一个值的其他人,您需要向前看:

def 前瞻(可迭代):"""传递给定迭代中的所有值,由当前值之后是否还有更多值的信息(True),或者如果它是最后一个值 (False)."""# 获取一个迭代器并拉取第一个值.它 = 迭代(可迭代)上一个 = 下一个(它)# 运行迭代器直到耗尽(从第二个值开始).对于其中的 val:# 报告*前一个*值(更多).最后屈服,真最后 = val# 报告最后一个值.最后屈服,假

然后你可以这样使用它:

<预><代码>>>>对于我,has_more in lookahead(range(3)):...打印(我,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

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

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