您可以使用带有递归的函数式编程风格,首先将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,以便使用递归函数方法仍然高效且可读。我也会尽量避免在循环内产生副作用。