单列表迭代与多列表理解 [英] Single list iteration vs multiple list comprehensions

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

问题描述

我有一个数据列表,我需要将其中的某些元素复制到几个不同的列表中.进行列表的单次迭代还是执行多个列表理解会更好

I have a list of data for which I need to copy some of it's elements into a couple of different lists. Would it be better to do a single iteration of the list or perform multiple list comprehensions

例如

def split_data(data):
    a = []
    b = []
    c = []
    for d in data:
        if d[0]   >   1 : a.append(d)
        if d[1]   == 'b': b.append(d)
        if len(d) ==  3 : c.append(d)

    return a, b, c

def split_data(data):
    a = [d for d in data if d[0]   >   1 ]
    b = [d for d in data if d[1]   == 'b']
    c = [d for d in data if len(d) ==  3 ]

    return a, b, c

我知道执行列表操作的更多Python方式是列表理解,但是在这种情况下是这种情况吗?

I know the more pythonic way of doing this is with list comprehensions, but is that the case in this instance?

推荐答案

只需使用多个if语句对数据进行一次迭代,而后面的代码则需要对数据进行3次迭代.我相信列表理解将在大多数时间内以与数据相等的迭代次数获胜.

in your 1st example code, it only need to iterate through the data once with multiple if statement, while the later code need to iterate through the data 3 times. I believe list comprehension will win most of the time with equal number of iteration over data.

对于像您的示例这样的简单操作,我宁愿使用列表理解方法,当操作变得更加复杂时,出于代码可读性的考虑,也许其他方法会更好.

For simple operation like your example, i would prefer list comprehension method, when the operation become more complex, maybe the other would be better for the sake of code readability.

关于2函数的一些基准测试应该告诉您更多信息. 基于我使用一些虚拟数据集对这两个函数的快速基准测试,如下所示.此运行时可能并不总是正确,具体取决于数据集

Some benchmarking over the 2 function should tell you more. Based on my quick benchmarking over those 2 function using some dummy data set getting runtime as below. This runtime might not always true depends on the data set

# without list comprehension
>>> timeit.timeit('__main__.split_data([("a","b")] * 1000000)', 'import __main__', number=1)
0.43826036048574224

# with list comprehension
>>> timeit.timeit('__main__.split_data([("a","b")] * 1000000)', 'import __main__', number=1)
0.31136326966964134

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

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