有效地迭代python嵌套列表 [英] iterate python nested lists efficiently

查看:56
本文介绍了有效地迭代python嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python进行网络流量监控器项目.不太熟悉Python,因此我在这里寻求帮助.

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 traffic, I wrote it this way:

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

netdata是一个由嵌套列表组成的列表,其格式如下:

netdata is a list consisting of nested lists, its format is like this:

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

此处t表示力矩,而f是流.但是,我只想在此时此刻始终保持这些f不变,我想知道如何获得有效的代码.

Here t represents the moment and f is the flow. 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.

经过一些搜索,我想我需要使用创建一个流量列表(2个元素),然后使用zip函数同时迭代两个列表,但是我很难编写正确的列表.由于我的netdata列表很长,因此效率也很重要.

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. Since my netdata is a very long list, efficiency is also very important.

如果有任何令人困惑的地方,请告诉我,我会尽力澄清. 感谢您的帮助

If there is anything confusing, let me know, I will try to clarify. Thanks for help

推荐答案

除了对代码的次要修复(@Zero Piraeus提出的问题)之外,您的问题还可能被

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

示例:

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]

使其起作用的关键是递归,而使其有效工作的关键是使用生成器(关键字yield提供提示).生成器将遍历您的列表列表,逐项返回您,而无需复制数据或创建整个新列表(除非您像整个示例那样使用整个生成器将结果分配给列表)

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)

使用迭代器和生成器可能是一个难以理解的概念(主要是关键字yield).查看此绝佳答案,以完全理解它们

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

这篇关于有效地迭代python嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆