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

例如在C语言中:

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

在Python中如何做到这一点?


当前回答

最好的办法是使用numpy库。

from numpy import ndarray

a = ndarray((5,),int)

其他回答

你可以使用:

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

最好的办法是使用numpy库。

from numpy import ndarray

a = ndarray((5,),int)

这样做:

>>> d = [ [ None for y in range( 2 ) ] for x in range( 2 ) ]
>>> d
[[None, None], [None, None]]
>>> d[0][0] = 1
>>> d
[[1, None], [None, None]]

其他的解决方案会导致这样的问题:

>>> d = [ [ None ] * 2 ] * 2
>>> d
[[None, None], [None, None]]
>>> d[0][0] = 1
>>> d
[[1, None], [1, None]]

您可以尝试使用Descriptor来限制大小

class fixedSizeArray(object):
    def __init__(self, arraySize=5):
        self.arraySize = arraySize
        self.array = [None] * self.arraySize

    def __repr__(self):
        return str(self.array)

    def __get__(self, instance, owner):
        return self.array

    def append(self, index=None, value=None):
        print "Append Operation cannot be performed on fixed size array"
        return

    def insert(self, index=None, value=None):
        if not index and index - 1 not in xrange(self.arraySize):
            print 'invalid Index or Array Size Exceeded'
            return
        try:
            self.array[index] = value
        except:
            print 'This is Fixed Size Array: Please Use the available Indices'


arr = fixedSizeArray(5)
print arr
arr.append(100)
print arr
arr.insert(1, 200)
print arr
arr.insert(5, 300)
print arr

输出:

[None, None, None, None, None]
Append Operation cannot be performed on fixed size array
[None, None, None, None, None]
[None, 200, None, None, None]
This is Fixed Size Array: Please Use the available Indices
[None, 200, None, None, None]

我发现很容易做的一件事是我设置一个数组 例如,我喜欢的大小的空字符串

代码:

import numpy as np

x= np.zeros(5,str)
print x

输出:

['' '' '' '' '']

希望这对你有帮助:)