Python: flatten nested lists with indices

后端 未结 3 967
被撕碎了的回忆
被撕碎了的回忆 2021-02-13 16:01

Given a list of arbitrairly deep nested lists of arbitrary size, I would like an flat, depth-first iterator over all elements in the tree, but with path indicies as well such th

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-13 16:59

    Recursion is good approach for flattening deeply nested lists. Your implementation is also well done. I would suggest modifying it with this similar recipe as follows:

    Code

    from collections import Iterable
    
    
    def indexed_flatten(items):
        """Yield items from any nested iterable."""
        for i, item in enumerate(items):
            if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
                for item_, idx in indexed_flatten(item):
                    yield item_, (i,) + idx
            else:
                yield item, (i,)
    
    
    lst = [[[1, 2, 3], [4, 5]], [6], [7, [8, 9]], 10]
    list(indexed_flatten(lst))
    

    Output

    [(1, (0, 0, 0)),
     (2, (0, 0, 1)),
     (3, (0, 0, 2)),
     (4, (0, 1, 0)),
     (5, (0, 1, 1)),
     (6, (1, 0)),
     (7, (2, 0)),
     (8, (2, 1, 0)),
     (9, (2, 1, 1)),
     (10, (3,))]
    

    This robustly works with many item types, e.g. [[[1, 2, 3], {4, 5}], [6], (7, [8, "9"]), 10].

提交回复
热议问题