当使用for循环迭代时,我如何处理输入的最后一个元素?特别是,如果有代码应该只出现在元素之间(而不是在最后一个元素之后),我该如何构造代码?
目前,我写的代码是这样的:
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
我如何简化或改进它?
假设input是一个迭代器,下面是使用itertools中的tee和izip的方法:
from itertools import tee, izip
items, between = tee(input_iterator, 2) # Input must be an iterator.
first = items.next()
do_to_every_item(first) # All "do to every" operations done to first item go here.
for i, b in izip(items, between):
do_between_items(b) # All "between" operations go here.
do_to_every_item(i) # All "do to every" operations go here.
演示:
>>> def do_every(x): print "E", x
...
>>> def do_between(x): print "B", x
...
>>> test_input = iter(range(5))
>>>
>>> from itertools import tee, izip
>>>
>>> items, between = tee(test_input, 2)
>>> first = items.next()
>>> do_every(first)
E 0
>>> for i,b in izip(items, between):
... do_between(b)
... do_every(i)
...
B 0
E 1
B 1
E 2
B 2
E 3
B 3
E 4
>>>
我在下面分享了两个简单的方法来查找循环的结束。
方法1:
num_list = [1, 2, 3, 4]
for n in num_list:
if num_list[-1] == n:
print('this is the last iteration of the loop')
方法2:
num_list = [1, 2, 3, 4]
loop_count = len(num_list) - 1 # 3
for index, num in enumerate(num_list):
if index == loop_count:
print('this is the last iteration of the loop')