1

I have, for a NLP application a list of lists which has many levels in it and i want them all flattened and extracted into a single list. This is equivalent of unlist in R programming language. Most of the code in stack-overflow allows flattening of list only one or two level down. Can anyone help me to do that ?

x = [1,2,[3,[4,5,21,[32,12]]]] to x = [1,2,3,4,5,21,32,12]

1 Answers1

1

This is a very big problem in python, because there is no function that is equivalent to unlist function in R. To be able to extract multi-level lists with-in a list to a single list, which is also called flattening of a list. Most questions on stack-overflow does not answer this: How to make a flat list out of list of lists? I present here some code in python that uses simple idea of Recursion to accomplish this:

def unlist(m):
  q = []
  for x in m:
    if (type(x) is list):
      for y in x:
        q.append(y)
      continue
    q.append(x)
  for i in range(len(q)):
    if (type(q[i]) is not list):
      if (i == (len(q)-1)):
        return q
      continue
    else:
      break
  for elem in q:
    if (type(elem) is list):
      z = unlist(elem)
      q.remove(elem)
      for item in z:
        q.append(item)
  return q

This will flatten any level of list with-in list to a single list.

x = [1,2,[3,[4,5,21, [32,12]]]] to x = [1,2,3,4,5,21,32,12].