Home > Blockchain >  My code works but need an elegant way to produce sub-lists out of a list
My code works but need an elegant way to produce sub-lists out of a list

Time:04-11

As below, I have a list called lst of 2 elements that represent some slot indices for me. I want obtain sub-lists from this that are produced based on the value of slotss as below.

lst=[0,10]
slotss=4
out_lst= [0,3],[1,4],[2,5],[3,6],[4,7],[5,8],[6,9] (but not 7,10)

My below code works but I need an elegant way of doing this. Because the profiler shows that the code spends more time in the above task.

out_lst=[]
    for u in range(len(lst)):        
                    
        condi1=lst[u][0]
        condi2=lst[u][1]

        break_signal=0
        cnt2=condi1
        cnt1=condi1
        for i in range(condi2 1):
            in_lst=[]
    
            if i!=0:
                cnt2=cnt2 1
            
            for j in range(2):
                if cnt1>=condi2:
                    break_signal=1
                    break
                else:
                    in_lst.append(cnt1)
                    cnt1=cnt1 slotss-1
                    
            
            if break_signal==1:
                break
            else:
                cnt1=cnt2 1
        
            out_lst.append(in_lst)

CodePudding user response:

You can just write a list comprehension to achieve the result you want:

lst = [0, 10]
slotss = 4

out_lst = [[start, start   (slotss - 1)] for start in range(lst[0], lst[1] - (slotss - 1))]

Output:

[[0, 3], [1, 4], [2, 5], [3, 6], [4, 7], [5, 8], [6, 9]]

CodePudding user response:

Another version:

out = list(enumerate(range(slotss - 1, lst[1]), lst[0]))
print(out)

Prints:

[(0, 3), (1, 4), (2, 5), (3, 6), (4, 7), (5, 8), (6, 9)]

CodePudding user response:

You can make this expression more concise using tuple() and a generator expression:

[start, end] = [0, 10]
size = 4

tuple([i, i   size - 1] for i in range(start, end - size   1)) 

This outputs:

([0, 4], [1, 5], [2, 6], [3, 7], [4, 8], [5, 9])
  • Related