我想知道我如何可以初始化一个数组(或列表),尚未与值填充,有一个定义的大小。
例如在C语言中:
int x[5]; /* declared without adding elements*/
在Python中如何做到这一点?
我想知道我如何可以初始化一个数组(或列表),尚未与值填充,有一个定义的大小。
例如在C语言中:
int x[5]; /* declared without adding elements*/
在Python中如何做到这一点?
当前回答
如果你正在使用字节,你可以使用内置的bytearray。如果使用其他整型,请查看内置数组。
明确地理解列表不是数组。
例如,如果你试图创建一个缓冲区来读取文件内容,你可以使用bytearray,如下所示(还有更好的方法,但这个例子是有效的):
with open(FILENAME, 'rb') as f:
data = bytearray(os.path.getsize(FILENAME))
f.readinto(data)
在这个代码片段中,bytearray内存被预先分配为固定长度的FILENAMEs大小(以字节为单位)。这种预分配允许使用缓冲区协议更有效地将文件读入可变缓冲区,而无需复制数组。还有更好的方法来做到这一点,但我相信这为你的问题提供了一个答案。
其他回答
我想通过发布一个示例程序及其输出来帮助你
计划:
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
希望能有所帮助!!;)
您可以尝试使用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]
这样做:
>>> 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]]
>>> import numpy
>>> x = numpy.zeros((3,4))
>>> x
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
>>> y = numpy.zeros(5)
>>> y
array([ 0., 0., 0., 0., 0.])
X是二维数组,y是一维数组。它们都是0初始化的。
最好的办法是使用numpy库。
from numpy import ndarray
a = ndarray((5,),int)