Search code examples
pythonloopsfor-loopnested-loops

How to break and start from where I ended in a nested loop


I want to run this loop over a list basically it searches for a number in my a range till it finds it search for the next number in the following iterations but instead it starts over again

This is my code

z = [30,84,126,135,137,179,242,342,426]
c=[]
for m in z:
    for i in range(1,1002, 7):
        if m  in range(i, i+7):
            c.append(m%7)
            break
        elif m not in range(i, i+7):
            c.append(0)
print len(c) # outputs 246 

but len(c) should be equal to 143, how do I fix this?


Solution

  • while a generator seemed to answer the question, there is a better tool for the programming problem: itertools.groupby

    from itertools import groupby
    
    
    z = [1,2,3, 30,84,126,135,136,137,140,141,179,242,342,426]
    
    g = dict([[k, [*g]] for k, g in groupby(z, key=lambda x: (x-1)//7)])
    
    d = [((tuple(g[i]) if len(g[i]) > 1 else g[i][0]) if (i in g) else 0)
         for i in range(0, 143)]
    

    ran against my 1st answer's code: (do use the same z, it has been changed)

    c == d
    Out[278]: True
    

    see how well matched itertools.groupby is look at the dict wrapped groupby result:

    g
    Out[279]: 
    {0: [1, 2, 3],
     4: [30],
     11: [84],
     17: [126],
     19: [135, 136, 137, 140],
     20: [141],
     25: [179],
     34: [242],
     48: [342],
     60: [426]}
    

    (the above works in 3.6, the [*g] and dictionary key test (i in g) may be different in 2.7)