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

查看:22
本文介绍了在 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

结论.这几乎不重要.

过早优化是万恶之源.

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

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