Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to deep flatten a list of messy arrays?

I have a Python list/array of really messy lists/arrays that either contains a list, array, or an empty list/array. Is there a simple operation I can use to completely flatten it to return me a 1D array?

Here would be an example that might not be correct

a = np.array([[1,2,3],
              [],
              [np.array([1,2,3])],
              [np.array([1,2,[]])]])

I say might not be correct because I cant think of a way to make it even messier. There would only be numbers in the data. No strings etc.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But all I need is to convert it to a 1D array where each entry contains a single value; neither a list nor an array. Is there such a function or do I need to iterate the the array and do a check for every element?

>Solution :

You could write a recursive function that goes through the nested iterable items to flatten the structure:

def flatten(a):
    try:
        return [item for flat in map(flatten,a) for item in flat]
    except: 
        return [a]

ouput:

import numpy as np

a = np.array([[1,2,3],
              [],
              [np.array([1,2,3])],
              [np.array([1,2,[]])]])

print(flatten(a))

[1, 2, 3, 1, 2, 3, 1, 2]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading