在python的for循环的最后迭代中执行一个操作 [英] Perform an operation during the last iteration of a for loop in python

查看:250
本文介绍了在python的for循环的最后迭代中执行一个操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个解析文本文件的循环:

  for line in file:
if如果item.startwith('ID ='):
* stuff *
如果是last_iteration_of_loop,则line.startswith('TK'):
for line.split
* stuff *

我需要做一些分配,第二个循环的最后一个迭代。有没有办法来检测这个,或者一种方法来知道是否在最后一项 line.split()?注意,第二个for循环中的项是字符串,我的内容在运行时是未知的,所以我不能查找特定的字符串作为标志让我知道我在最后。



谢谢!

解决方案

只要引用for循环的最后一行:

<$对于line.split()中的项目,line.startswith('TK'):
item = None

pre> b $ b if item.startwith('ID ='):
#* stuff *

如果item不是None:
#* stuff *

在for循环之外,变量仍然可用:

 >>>我在范围(5):
...打印我
...
0
1
2
3
4
>>> print'last:',i
last:4

请注意,如果您的文件为空(不通过循环迭代) item 不会被设置;这就是为什么我们在循环之前设置 item = None ,然后测试如果item不是None 之后。



如果您必须拥有与您的测试匹配的最后一个项目,请将其存储在一个新变量中:

line.startwith('TK'):
lastitem = None
用于line.split()中的项目的文件中的

 
if item.startwith('ID ='):
lastitem = item
* stuff *

如果lastitem不是None:
# * stuff *

演示第二个选项:

 >>> lasti = None 
>>> (5):
... if i%2 == 0:
... lasti = i
...
>>> lasti
4


I have a loop that is parsing lines of a text file:

for line in file:
    if line.startswith('TK'):
        for item in line.split():
            if item.startwith('ID='):
                *stuff*
            if last_iteration_of_loop
                *stuff*

I need to do a few assignments, but I cant do them until the last iteration of the second for loop. Is there a way to detect this, or a way to know if im at the last item of line.split()? As a note, the items in the second for loop are strings, and I the contents of them are unknown at runtime, so i cant look for a specific string as flag to let me know im at the end.

Thanks!

解决方案

Just refer to the last line outside the for loop:

for line in file:
    if line.startswith('TK'):
        item = None
        for item in line.split():
            if item.startwith('ID='):
                # *stuff*

        if item is not None:
            # *stuff*

The item variable is still available outside the for loop:

>>> for i in range(5):
...     print i
... 
0
1
2
3
4
>>>  print 'last:', i
last: 4

Note that if your file is empty (no iterations through the loop) item will not be set; this is why we set item = None before the loop and test for if item is not None afterwards.

If you must have the last item that matched your test, store that in a new variable:

for line in file:
    if line.startswith('TK'):
        lastitem = None
        for item in line.split():
            if item.startwith('ID='):
                lastitem = item
                # *stuff*

        if lastitem is not None:
             # *stuff*

Demonstration of the second option:

>>> lasti = None
>>> for i in range(5):
...     if i % 2 == 0:
...         lasti = i
...
>>> lasti
4

这篇关于在python的for循环的最后迭代中执行一个操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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