Home > Back-end >  Triple list comprehension (flat list out of a list of arrays of lists of lists)
Triple list comprehension (flat list out of a list of arrays of lists of lists)

Time:11-16

I've been scouring Google for an answer to this question, and have so far only seen similar results for different problems.

My list of lists of lists has the structure as follows (edit: arrays are numpy): [array([[item]]), array([[item2]]), ...]

As you can see, it is not inconsistent formatting (it's a result of using numpy column vectors in a previous operation). I would like to flatten this to a simple list of values using a 1-line list comprehension. Similar problems include variable size sub- or sub-sub-lists, which I do not have to worry about.

The "solution" that would make the most sense to me: [item for sublist for arr in list for item in sublist in arr] But this doesn't work for syntax reasons, not to mention that I'm unsure if it goes deep enough.

I was wondering if this is even possible, and if anyone smarter than me could come up with a solution. Not time sensitive, we've settle for scatter plots...for now.

Cheers!

CodePudding user response:

If your arrays are of one element as you've shown, you can directly index down when you do your comprehension:

list_of_lists_of_lists = [[[item1]], [[item2]], ...]
[array[0][0] for array in list_of_lists_of_lists]

If your arrays are more complicated, you can do your nested for x in y statements, you just need to put them in the correct order:

list_of_lists_of_lists = [[[item1]], [[item2], [item5]], [[item3, item4]]]
[item for lists_of_lists in list_of_lists_of_lists for sublist in lists_of_lists for item in sublist]

Which will yield them in the order:

[item1, item2, item5, item3, item4]

Lastly, if you don't know how deep it goes but you do know the type of your items, you can always perform a recursive search:

test = [[[1]], [[2], [5]], [[[3], 4]], [[[[[[6]]]]]]]
result = list()
my_type = int
def generator(my_list, accumulator):
    if isinstance(my_list, my_type):
        accumulator.append(my_list)
        return
    for item in my_list:
        generator(item, accumulator)
gen(test, result)

Which will give you result = [1, 2, 5, 3, 4, 6]

  • Related