在python的for循环的最后迭代中执行一个操作 [英] Perform an operation during the last iteration of a for loop in python
问题描述
我有一个解析文本文件的循环:
for line in file:
if如果item.startwith('ID ='):
* stuff *
如果是last_iteration_of_loop,则line.startswith('TK'):
for line.split
* stuff *
我需要做一些分配,第二个循环的最后一个迭代。有没有办法来检测这个,或者一种方法来知道是否在最后一项 line.split()
?注意,第二个for循环中的项是字符串,我的内容在运行时是未知的,所以我不能查找特定的字符串作为标志让我知道我在最后。
谢谢!
只要引用for循环的最后一行: 在for循环之外, 请注意,如果您的文件为空(不通过循环迭代) 如果您必须拥有与您的测试匹配的最后一个项目,请将其存储在一个新变量中: 演示第二个选项: I have a loop that is parsing lines of a text file: 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 Thanks! Just refer to the last line outside the for loop: The Note that if your file is empty (no iterations through the loop) If you must have the last item that matched your test, store that in a new variable: Demonstration of the second option:
这篇关于在python的for循环的最后迭代中执行一个操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
<$对于line.split()中的项目,line.startswith('TK'):
item = None
:
pre> b $ b if item.startwith('ID ='):
#* stuff *
如果item不是None:
#* stuff *
项
变量仍然可用:
>>>我在范围(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
for line in file:
if line.startswith('TK'):
for item in line.split():
if item.startwith('ID='):
*stuff*
if last_iteration_of_loop
*stuff*
line.split()
? As a note, the item
s 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.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*
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
item
will not be set; this is why we set item = None
before the loop and test for if item is not None
afterwards.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*
>>> lasti = None
>>> for i in range(5):
... if i % 2 == 0:
... lasti = i
...
>>> lasti
4