Skip iterations in enumerated list object (python)

前端 未结 6 2150
清歌不尽
清歌不尽 2021-02-14 19:33

I have the code

for iline, line in enumerate(lines):
    ...
    if :
        

I would like, as you c

6条回答
  •  一生所求
    2021-02-14 19:49

    You could use a functional programming style with recursion, first by putting the necessary parts of your for loop into a function:

    def my_function(iline, line, rest_of_lines, **other_args):
        do_some_side_effects(iline, line, **other_args)
    
        if rest_of_lines == []:
            return 
    
        increment = 5 if  else 1
        return my_function(iline+increment, 
                           rest_of_lines[increment-1], 
                           rest_of_lines[increment:],
                           **other_args)
    

    Optionally, if it doesn't need to return anything, you can just adjust those lines of code to be function calls, and the return result will be None.

    Then some place you actually call it:

    other_args = get_other_args(...)
    
    my_function(0, lines[0], lines[1:], **other_args)
    

    If you need the function to return something different for each index, then I would suggest modifying this slightly to account for the output data structure you want. In that case, you might want to pass the inner result of do_some_side_effects back into the recursive function call so it can build up the result.

    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  else 1
        return my_function(iline+increment, 
                           rest_of_lines[increment-1], 
                           rest_of_lines[increment:],
                           new_output,
                           **other_args)
    

    Then to call

    other_args = get_other_args(...)
    
    empty_output = get_initial_data_structure(...)
    
    full_output = my_function(0, lines[0], lines[1:], empty_output, **other_args)
    

    Note that in Python, because of the way most of the basic data structures are implemented, this programming style is not going to gain you efficiency, and in the context of other object oriented code it may even be bad style to complicate things beyond the simple while solution.

    My advice: use the while loop, though I would tend to structure my projects and APIs so that using a recursive functional approach will still be efficient and readable. I would also try not to allow side effects inside the loop.

提交回复
热议问题