Python - 创建具有初始容量的列表 [英] Python - Create a list with initial capacity

查看:108
本文介绍了Python - 创建具有初始容量的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样的代码经常发生:

l = []
while foo:
    #baz
    l.append(bar)
    #qux

您将要将数千个元素添加到列表中,因为列表将不得不进行大小调整以适应新元素。

This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements.

在Java中,您可以创建一个具有初始容量的ArrayList。如果你有一些想法,你的列表将会有多大,这会更有效率。

In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient.

我知道这样的代码通常可以重新列入一个列表理解。如果for / while循环非常复杂,那么这是不可行的。对于我们Python程序员有什么等同的?

I understand that code like this can often be re-factored into a list comprehension. If the for/while loop is very complicated, though, this is unfeasible. Is there any equivalent for us Python programmers?

推荐答案

def doAppend( size=10000 ):
    result = []
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result.append(message)
    return result

def doAllocate( size=10000 ):
    result=size*[None]
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result[i]= message
    return result

结果。 (评估每个功能144次,平均持续时间)

Results. (evaluate each function 144 times and average the duration)

simple append 0.0102
pre-allocate  0.0098

结论。几乎没关系

过早优化是所有邪恶的根源。

Premature optimization is the root of all evil.

这篇关于Python - 创建具有初始容量的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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