现在我正在使用一个列表,并期待类似的东西:

verts = list (1000)

我应该用数组代替吗?


当前回答

Wanting to initalize an array of fixed size is a perfectly acceptable thing to do in any programming language; it isn't like the programmer wants to put a break statement in a while(true) loop. Believe me, especially if the elements are just going to be overwritten and not merely added/subtracted, like is the case of many dynamic programming algorithms, you don't want to mess around with append statements and checking if the element hasn't been initialized yet on the fly (that's a lot of code gents).

对象= [0 for x in range(1000)]

这将为程序员试图实现的目标工作。

其他回答

你可以这样做:

verts = list(xrange(1000))

这将为您提供一个大小为1000个元素的列表,并且恰巧初始化值为0-999。由于list首先执行__len__来调整新列表的大小,因此应该相当有效。

Wanting to initalize an array of fixed size is a perfectly acceptable thing to do in any programming language; it isn't like the programmer wants to put a break statement in a while(true) loop. Believe me, especially if the elements are just going to be overwritten and not merely added/subtracted, like is the case of many dynamic programming algorithms, you don't want to mess around with append statements and checking if the element hasn't been initialized yet on the fly (that's a lot of code gents).

对象= [0 for x in range(1000)]

这将为程序员试图实现的目标工作。

这样的:

 lst = [8 for i in range(9)]

创建一个列表,元素初始化8

但这:

lst = [0] * 7

会创建7个包含一个元素的列表吗

我首先想到的是:

verts = [None]*1000

但是你真的需要初始化它吗?

如果不了解问题领域的更多信息,就很难回答您的问题。 除非你确定你需要做更多的事情,否则python初始化列表的方法是:

verts = []

您是否真的看到了性能问题?如果有,性能瓶颈是什么? 不要试图去解决一个你没有的问题。动态地将数组填充到1000个元素的性能代价可能与您真正试图编写的程序完全无关。

数组类是有用的,如果你的列表中的东西总是一个特定的基本固定长度类型(例如char, int, float)。但是,它也不需要预初始化。