Creating a list of lists based on other list

Question:

From the following list:

values = [('on',1),('e1',2),('e2',3),('on',4),('on',5),('e1',6),('e2',7),('on',8)]

I’m attempting to create a list of lists containing:

[('on',1),('e1',2),('e2',3),('on',4)],
[('on',5),('e1',6),('e2',7)('on',8)]

The logic is: find an on, continue until find another on and store all intermediary list elements in a sublist.

Here is my code:

%reset -f

values = [('on',1),('e1',2),('e2',3),('on',4),('on',5),('e1',6),('e2',7),('on',8)]

    t_l = []
    for i,v in enumerate(values): 
        temp_list = []
        if v[0] == 'on' : 
            temp_list.append(v)
            for ii, v2 in enumerate(values, start=i+1):
                if v2[0] == 'on' : 
                    t_l.append(temp_list)
                    break
                else : 
                    temp_list.append(v2)
    
    t_l

t_l contains:

[[('on', 1)], [('on', 4)], [('on', 5)], [('on', 8)]]

The begin positions appear to be calculated correctly but intermediary values are not.

This line is not behaving as expected:

for ii, v2 in enumerate(values, start=i+1):

The start position is not being used, for example if I set start=3000 an exception is not thrown, so it appears I’ve not configured start correctly.

Asked By: blue-sky

||

Answers:

You can do it with simple if else statements:

new_lst=[]
l=[]
x=0
for i in values:
    if i[0]=='on' and x==0:
        l.append(i)
        x=1
    elif i[0]!='on' and x==1:
        l.append(i)
    else:
        l.append(i)
        x=0
        new_lst.append(l)
        l=[]
print(new_lst)
Answered By: zoldxk
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.