简体   繁体   English

有效地迭代python嵌套列表

[英]iterate python nested lists efficiently

I am working on a network traffic monitor project in Python. 我正在使用Python进行网络流量监控项目。 Not that familiar with Python, so I am seeking help here. 不熟悉Python,所以我在这里寻求帮助。

In short, I am checking both in and out traffic, I wrote it this way: 简而言之,我正在检查流量和流量,我这样写:

for iter in ('in','out'):
        netdata = myhttp()
        print data

netdata is a list consisting of nested lists, its format is like this: netdata是一个由嵌套列表组成的列表,其格式如下:

[ [t1,f1], [t2,f2], ...]

Here t represents the moment and f is the flow. 这里t表示时刻, f表示流量。 However I just want to keep these f at this moment for both in and out, I wonder any way to get an efficient code. 但是我只想在这个时刻保留这些f进行内外,我想知道如何获得有效的代码。

After some search, I think I need to use create a list of traffic(2 elements), then use zip function to iterate both lists at the same time, but I have difficulty writing a correct one. 经过一些搜索,我认为我需要使用创建流量列表(2个元素),然后使用zip函数同时迭代这两个列表,但是我很难写出正确的列表。 Since my netdata is a very long list, efficiency is also very important. 由于我的netdata是一个很长的列表,效率也非常重要。

If there is anything confusing, let me know, I will try to clarify. 如果有任何令人困惑的事情,请告诉我,我会尽力澄清。 Thanks for help 感谢帮助

Apart from minor fixes on your code (the issues raised by @Zero Piraeus), your question was probably answered here . 除了代码的小修复(@Zero Piraeus提出的问题),你的问题可能在这里得到解答。 A possible code to traverse a list of lists in N degree (a tree) is the following: 遍历N度(树)列表的可能代码如下:

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). 使其工作的关键是递归,并且使其有效工作的关键是使用生成器(关键字yield给出提示)。 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). 使用迭代器和生成器可以理解奇怪的概念(主要是关键字yield )。 Checkout this great answer to fully understand them 查看这个很好的答案,以完全理解它们

The code you've shown doesn't make a great deal of sense. 你展示的代码没有多大意义。 Here's what it does: 这是它的作用:

  • Iterate through the sequence 'in', 'out' , assigning each of those two strings in turn to the variable iter (masking the built-in function iter() in the process) on its two passes through the loop. 迭代序列'in', 'out' ,将这两个字符串中的每一个依次分配给变量iter (在过程中屏蔽内置函数iter() ),在它的两次遍历循环中。

  • Completely ignore the value of iter inside the loop. 完全忽略循环中iter的值。

  • Assign the result of myhttp() to the variable netdata on each pass through the loop. 每次循环myhttp()的结果分配给变量netdata

  • Completely ignore the value of netdata , and instead attempt to print the undefined variable data on each pass through the loop. 完全忽略netdata的值,而是尝试在每次循环中打印未定义的变量data

It's possible, given the nested list you describe, that you want something like this: 考虑到您描述的嵌套列表,您可能需要这样的内容:

for t, f in myhttp():
    print t
    print f
    # ... or whatever you want to do with those values.

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. 它只是一个Python 3功能。

# 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM