How do I convert a flat list to a list of lists based on value of the elements in python3?

Viewed 85

I have a list arr=[1,-1,4,-1,4,2]

Is there a way to convert it to [[1],[4],[4,2]]?

Basically the -1 indicates where a sub-list ends

I tried

number_of_sublists=arr.count(-1)
lst=[[]]*(number_of_sublists+1)
    
idx=0
for i in arr:
    print(idx)
    if i==-1:
        idx+=1
    else:
        lst[idx].append(i)
print(lst)

but it is giving me the output

[[1,4,4,2],[1,4,4,2],[1,4,4,2]]

Why is this happening

4 Answers

Try this:

arr=[1,-1,4,-1,4,2]
newarr = [[]]
for i in arr:
    if i != -1:
        newarr[-1].append(i)
    else:
        newarr.append([])
print(newarr)

Output:

[[1], [4], [4, 2]]

You can use itertols.groupby:

from itertools import groupby

arr = [1, -1, 4, -1, 4, 2]

[[*g] for k, g in groupby(arr, key=(-1).__ne__) if k]
# [[1], [4], [4, 2]]

All the answers provided work for your task, but if you want to know why your original code did not work, it is because how you are declaring the list lst.

lst=[[]]*(number_of_sublists+1)

By doing this, you are repeating the same list at each of the positions of lst, that is, yo have made number_of_sublists+1 references to the same list. So when you modify one of them, you are actually modifying all at the same time.

You could simply change the declaration to this and that would solve your problem:

lst = [[] for _ in range(number_of_sublists+1)]

try the below

arr = [1, -1, 4, -1, 4, 2]
result = [[]]
create_new_list = False
for x in arr:
    if x == -1:
        create_new_list = True
    else:
        if create_new_list:
            result.append([])
            create_new_list = False
        result[-1].append(x)
print(result)

output

[[1], [4], [4, 2]]
Related