8

How can I convert:

THIS = \
['logging',
 ['logging', 'loggers',
  ['logging', 'loggers', 'MYAPP',
   ['logging', 'loggers', 'MYAPP', '-handlers'],
   ['logging', 'loggers', 'MYAPP', 'propagate']
  ]
 ],
 ['logging', 'version']
]

into:

THAT = [
    ['logging'],
    ['logging', 'version'],
    ['logging', 'loggers'],
    ['logging', 'loggers', 'MYAPP'],
    ['logging', 'loggers', 'MYAPP', '-handlers'],
    ['logging', 'loggers', 'MYAPP', 'propagate']
]

in python (it doesn't need to be sorted, just flattened)?

I've tried lots of things but can't find how to solve this.

4

2 Answers 2

3

Solved with recursive generator

def flatten(items):
    non_list_items = []

    for item in items:
        if isinstance(item, list):
            for inner_item in flatten(item):
                yield inner_item
        else:
            non_list_items.append(item)

    yield non_list_items

Testing against your input:

from pprint import pprint

>>> pprint(sorted(flatten(THIS)))
[['logging'],
 ['logging', 'loggers'],
 ['logging', 'loggers', 'MYAPP'],
 ['logging', 'loggers', 'MYAPP', '-handlers'],
 ['logging', 'loggers', 'MYAPP', 'propagate'],
 ['logging', 'version']]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I've been trying for ages to get this
2

This is where a recursive function really shines:

def flatten(myList):
  def inner(current, acc):
    items = []
    for x in myList:
      if isinstance(x, list):
        acc.extend(inner(x, []))
      else:
        items.append(x)
    acc.extend(items)
    return acc

  return inner(myList, [])

which I believe should do the trick.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.