在python中初始化一个固定大小的数组[重复]

问题描述

||                                                                                                                   这个问题已经在这里有了答案:                                                      

解决方法

您可以使用:
>>> lst = [None] * 5
>>> lst
[None,None,None]
    ,为什么这些问题没有得到显而易见的答案?
a = numpy.empty(n,dtype=object)
这将创建一个长度为n的数组,可以存储对象。不能调整大小或附加。特别是,它不会通过填充其长度来浪费空间。这与Java的Python等效
Object[] a = new Object[n];
如果您对性能和空间非常感兴趣,并且知道您的数组将仅存储某些数字类型,则可以将dtype参数更改为其他值,例如int。然后numpy将这些元素直接打包到数组中,而不是使数组引用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]]
其他解决方案将导致此类问题:
>>> d = [ [ None ] * 2 ] * 2
>>> d
[[None,[1,None]]
    ,最好的选择是使用numpy库。
from numpy import ndarray

a = ndarray((5,),int)
    ,一个简单的解决方案是
x = [None]*length
,但是请注意,它将所有列表元素初始化为
None
。如果尺寸确实固定,您也可以做do8ѭ。但严格来说,您不会以任何方式获得未定义的元素,因为这种困扰在Python中不存在。     ,
>>> import numpy
>>> x = numpy.zeros((3,4))
>>> x
array([[ 0.,0.,0.],[ 0.,0.]])
>>> y = numpy.zeros(5)   
>>> y
array([ 0.,0.])
x是2维数组,y是1维数组。它们都用零初始化。     ,
>>> n = 5                     #length of list
>>> list = [None] * n         #populate list,length n with n entries \"None\"
>>> print(list)
[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,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,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]
在附加的第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]
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]
    ,好吧,我想通过发布示例程序及其输出来帮助您 程序:
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],2]]
我希望这能清除您关于其声明的一些非常基本的概念。 要用其他一些特定值初始化它们,例如用
0
初始化它们,则可以将它们声明为:
x = [0]*10
希望能帮助到你..!! ;)     ,您可以尝试使用描述符来限制大小
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,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]
Append Operation cannot be performed on fixed size array
[None,None]
[None,200,None]
This is Fixed Size Array: Please Use the available Indices
[None,None]
    ,我觉得容易做的一件事是我设置了一个数组 例如,我喜欢的空字符串的大小 码:
import numpy as np

x= np.zeros(5,str)
print x
输出:
[\'\' \'\' \'\' \'\' \'\']
希望这会有所帮助:)     ,如果使用字节,则可以使用内置的
bytearray
。如果要使用其他整数类型,请查看内置的
array
。 特别要了解的是,
list
不是an23ѭ。 例如,如果您尝试创建一个缓冲区以将文件内容读入,则可以按以下方式使用字节数组(有更好的方法可以执行此操作,但该示例是有效的):
with open(FILENAME,\'rb\') as f:
    data = bytearray(os.path.getsize(FILENAME))
    f.readinto(data)
在此摘要中,将以固定长度length28ѭ的大小(以字节为单位)预分配
bytearray
存储器。这种预分配允许使用缓冲区协议来更有效地将文件读取到可变缓冲区中,而无需数组副本。还有更好的方法可以做到这一点,但是我相信这可以为您的问题提供一个答案。