0

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.

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?

Kong
  • 2,202
  • 8
  • 28
  • 56

1 Answers1

1

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]
Alain T.
  • 40,517
  • 4
  • 31
  • 51
  • thank you. I also found another generic solution which has worked https://stackoverflow.com/questions/2158395/flatten-an-irregular-arbitrarily-nested-list-of-lists I only found this thread a few minutes ago after trying various keywords in google – Kong Apr 21 '23 at 17:46