[SOLVED] Split a list into smaller lists depending on a certain value

Issue

Is there a way to split a list into smaller lists depending on a certain value.
To clarify what I want, I have a list of nparrays like this:

list_full = [[[some data_1], [1 0 0 0 0]], 
             [[some data_2], [0 1 0 0 0]],
             [[some data_3], [1 0 0 0 0]], 
             [[some data_4], [0 1 0 0 0]]]

I want to get lists like this :

list_1 = [[[some data_1], [1 0 0 0 0]], [[some data_3], [1 0 0 0 0]]] 
list_2 = [[[some data_2], [0 1 0 0 0]], [[some data_4], [0 1 0 0 0]]] 

As you can see, we regroup lists depends on list_full[i][1]

I have this code that I found in this toppic How to split a list into smaller lists python

from itertools import groupby

lst = [['ID1', 'A'],['ID1','B'],['ID2','AAA'], ['ID2','DDD']]
grp_lists = []
for i, grp in groupby(lst, key= lambda x: x[0]):
    grp_lists.append(list(grp))

But it didn’t working with me because I have numpy array as x[0], when I run this I got this error :

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Thank you.

Solution

I solved that by using the real represantation instead of one hot code. So I have added ‘np.argmax’ as following :

    for i, grp in groupby(list_full, key=lambda x: np.argmax(x[1], axis=-1)):
    grp_lists.append(list(grp))

Answered By – ProgrX

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *