iterate python nested lists efficiently

后端 未结 3 1608
没有蜡笔的小新
没有蜡笔的小新 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:33

    Apart from minor fixes on your code (the issues raised by @Zero Piraeus), your question was probably answered here. A possible code to traverse a list of lists in N degree (a tree) is the following:

    def traverse(item):
        try:
            for i in iter(item):
                for j in traverse(i):
                    yield j
        except TypeError:
            yield item
    

    Example:

    l = [1, [2, 3], [4, 5, [[6, 7], 8], 9], 10]
    print [i for i in traverse(l)]
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    

    The key to make it work is recursion and the key to make it work efficiently is using a generator (the keyword yield gives the hint). The generator will iterate through your list of lists an returning to you item by item, without needing to copy data or create a whole new list (unless you consume the whole generator assigning the result to a list, like in my example)

    Using iterators and generators can be strange concepts to understand (the keyword yield mainly). Checkout this great answer to fully understand them

提交回复
热议问题