我有验证码
for iline, line in enumerate(lines):
...
if <condition>:
<skip 5 iterations>
我希望您可以读懂,如果满足条件,则让for循环跳过5次迭代。我可以确定,如果满足条件,则“行”对象中还剩下5个或更多对象。
行存在字典数组,必须按顺序循环
iline = 0
while iline < len(lines):
line = lines[iline]
if <condition>:
place_where_skip_happened = iline
iline += 5
iline += 1
如果要遍历文件对象,则可以使用next跳过行或使行成为迭代器:
lines = iter(range(20))
for l in lines:
if l == 10:
[next(lines) for _ in range(5)]
print(l)
0
1
2
3
4
5
6
7
8
9
10
16
17
18
19
这实际上取决于您要迭代的内容和要执行的操作。
from itertools import islice
it = iter(enumerate(lines))
for iline, line in it:
if <condition>:
place_where_skip_happened = iline
next(islice(it,5 ,5), None)
print(line)
执行此操作的标准习惯是制作一个迭代器,然后使用使用者模式之一(请参阅here文档中的itertools
。]
例如:
from itertools import islice
lines = list("abcdefghij")
lit = iter(enumerate(lines))
for iline, line in lit:
print(iline, line)
if line == "c":
# skip 3
next(islice(lit, 3,3), None)
产生
0 a
1 b
2 c
6 g
7 h
8 i
9 j
正如Padraic Cunningham指出的那样,您可以使用while循环来执行此操作,也可以使用字典来替换if语句:
iline = 0
skip = {True:5, False:1}
while iline > len(lines):
line = lines[iline]
...
iline += skip[condition]
使用外部标志并在条件满足时进行设置,并在循环开始时进行检查:
ignore = 0
for iline, line in enumerate(lines):
if ignore > 0:
ignore -= 1
continue
print(iline, line)
if iline == 5:
ignore = 5
或明确地从枚举中提取5个元素:
enum_lines = enumerate(lines)
for iline, line in enum_lines:
print(iline, line)
if iline == 5:
for _, _ in zip(range(5), enum_lines):
pass
我个人比较喜欢第一种方法,但是第二种方法看起来更像Python。
您可以通过递归使用函数式编程风格,首先将for
循环的必要部分放入函数中:
def my_function(iline, line, rest_of_lines, **other_args):
do_some_side_effects(iline, line, **other_args)
if rest_of_lines == []:
return <some base case>
increment = 5 if <condition> else 1
return my_function(iline+increment,
rest_of_lines[increment-1],
rest_of_lines[increment:],
**other_args)
可选,如果不需要返回任何内容,则只需将这些代码行调整为函数调用,返回结果将为None
。
然后是您实际称呼的地方:
other_args = get_other_args(...)
my_function(0, lines[0], lines[1:], **other_args)
如果您需要该函数为每个索引返回不同的内容,那么我建议您对此做些修改,以解决您想要的输出数据结构。在这种情况下,您可能希望将do_some_side_effects
的内部结果传递回递归函数调用中,以便可以建立结果。
def my_function(iline, line, rest_of_lines, output, **other_args):
some_value = do_some_side_effects(iline, line, **other_args)
new_output = put_value_in_output(some_value, output)
# could be as simple as appending to a list/inserting to a dict
# or as complicated as you want.
if rest_of_lines == []:
return new_output
increment = 5 if <condition> else 1
return my_function(iline+increment,
rest_of_lines[increment-1],
rest_of_lines[increment:],
new_output,
**other_args)
然后打电话
other_args = get_other_args(...)
empty_output = get_initial_data_structure(...)
full_output = my_function(0, lines[0], lines[1:], empty_output, **other_args)
[请注意,在Python中,由于大多数基本数据结构的实现方式,这种编程风格不会提高您的效率,并且在其他面向对象的代码的背景下,将超出简单的while
解决方案。
我的建议:使用while
循环,尽管我倾向于结构化项目和API,以便使用递归功能方法仍将高效且易读。我也尽量不要在循环内产生副作用。
类似于已接受的答案…,只是不使用itertools
(恕我直言islice
不会提高可读性),再加上enumerate()
已经返回了迭代器,因此您根本不需要iter()
:
lines = [{str(x): x} for x in range(20)] # dummy data
it = enumerate(lines)
for i, line in it:
print(line)
if i == 10: # condition using enumeration index
[next(it, None) for _ in range(5)] # skip 5
最后一行可以选择扩展以提高可读性:
for _ in range(5): # skip 5
next(it, None)
None
中的next()
参数避免了没有足够多的项目要跳过的异常。 (对于原始问题,可以省略,因为OP写道:“我可以确定,如果满足条件,则lines
对象中还有5个或更多对象。”
如果跳过条件不是基于枚举索引,只需将列表视为FIFO队列并使用pop()
从列表中进行消费:
lines = [{str(x): x} for x in range(20)] # dummy data
while lines:
line = lines.pop(0) # get first item
print(line)
if <condition>: # some other kind of condition
[lines.pop(0) for _ in range(5)] # skip 5
和以前一样,最后一行可以有选择地扩展以提高可读性:
for _ in range(5): # skip 5
lines.pop(0)
((对于大型列表,请使用collections.deque
进行演奏。)