Recursive generator for flattening nested lists

前端 未结 5 1544
离开以前
离开以前 2020-12-03 12:04

I\'m a programming newbie and am having some trouble understanding an example from my python textbook (\"Beginning Python\" by Magnus Lie Hetland). The example is for a recu

5条回答
  •  离开以前
    2020-12-03 12:43

    I have added some instrumentation to the function:

    def flatten(nested, depth=0):
        try:
            print("{}Iterate on {}".format('  '*depth, nested))
            for sublist in nested:
                for element in flatten(sublist, depth+1):
                    print("{}got back {}".format('  '*depth, element))
                    yield element
        except TypeError:
            print('{}not iterable - return {}'.format('  '*depth, nested))
            yield nested
    

    Now calling

    list(flatten([[1,2],3]))
    

    displays

    Iterate on [[1, 2], 3]
      Iterate on [1, 2]
        Iterate on 1
        not iterable - return 1
      got back 1
    got back 1
        Iterate on 2
        not iterable - return 2
      got back 2
    got back 2
      Iterate on 3
      not iterable - return 3
    got back 3
    

提交回复
热议问题