我想知道我如何可以初始化一个数组(或列表),尚未与值填充,有一个定义的大小。

例如在C语言中:

int x[5]; /* declared without adding elements*/

在Python中如何做到这一点?


当前回答

>>> n = 5                     #length of list
>>> list = [None] * n         #populate list, length n with n entries "None"
>>> print(list)
[None, None, None, None, None]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, None, None, 1]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, None, 1, 1]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, 1, 1, 1]

或者一开始就什么都没有:

>>> n = 5                     #length of list
>>> list = []                 # create list
>>> print(list)
[]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1]

在append的第4次迭代中:

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1,1,1,1]

5及所有后续:

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1,1,1,1,1]

其他回答

我想通过发布一个示例程序及其输出来帮助你

计划:

t = input("")
x = [None]*t
y = [[None]*t]*t

for i in range(1, t+1):
    x[i-1] = i;

    for j in range(1, t+1):
        y[i-1][j-1] = j;

print x
print y

输出:

2
[1, 2]
[[1, 2], [1, 2]]

我希望这澄清了你对他们的宣言的一些非常基本的概念。 用其他特定的值初始化它们,比如用0..你可以将它们声明为:

x = [0]*10

希望能有所帮助!!;)

一个简单的解决方案是x = [None]*length,但请注意,它将所有列表元素初始化为None。如果大小是固定的,你也可以执行x=[None,None,None,None]。但严格来说,无论采用哪种方式,都不会得到未定义的元素,因为Python中不存在这种麻烦。

为什么这些问题没有得到显而易见的答案呢?

a = numpy.empty(n, dtype=object)

这将创建一个长度为n的数组,用于存储对象。它不能被调整大小或追加。特别是,它不会因为填充长度而浪费空间。这是Python中与Java相同的部分

Object[] a = new Object[n];

如果你真的对性能和空间感兴趣,并且知道你的数组只存储某些数值类型,那么你可以将dtype参数更改为其他一些值,比如int。然后numpy将这些元素直接打包到数组中,而不是使数组引用int对象。

你可以使用:

>>> lst = [None] * 5
>>> lst
[None, None, None, None, None]

最好的办法是使用numpy库。

from numpy import ndarray

a = ndarray((5,),int)