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

查看:93
本文介绍了使用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 refactored into a list comprehension. If the for/while loop is very complicated, though, this is unfeasible. Is there an 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天全站免登陆