iterate python nested lists efficiently

后端 未结 3 1612
没有蜡笔的小新
没有蜡笔的小新 2020-12-10 17:12

I am working on a network traffic monitor project in Python. Not that familiar with Python, so I am seeking help here.

In short, I am checking both in and out traff

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-10 17:49

    When trying one the the other answers, the function was unable to recurse, and so I modified it to not recurse. It still works quite quickly, and can handle large nested lists (at least as far as I can tell with my testing). It is a Python 3 only function.

    # Originally by Bruno Polaco
    def traverse(item, reverse=False):
        its = [item] #stack of items to-be-processed
        out = [] # Output (no longer generator)
        ite = False
        while len(its) > 0:
            it = its.pop()
            try: # Check if item is iterable
                iter(it)
                ite = not isinstance(it, str)
            except TypeError:
                ite = False
            if ite: # Do something with it
                for i in it:
                    its.append(i)
            else:
                out.append(it)
        if not reverse:
            out.reverse()
        return out
    

提交回复
热议问题