Initialising an array of fixed size in python
我想知道如何初始化一个数组(或列表),但要用值填充,才能有一个定义的大小。
例如,在C中:
1 | int x[5]; /* declared without adding elements*/ |
我该如何在python中做到这一点?
谢谢。
你可以使用:
1 2 3 | >>> lst = [None] * 5 >>> lst [None, None, None, None, None] |
为什么这些问题不能用显而易见的答案来回答呢?
1 | a = numpy.empty(n, dtype=object) |
这将创建一个长度为n的数组,该数组可以存储对象。它不能调整大小或附加到。尤其是,它不会通过填充长度来浪费空间。这是Java的等价物。
1 | Object[] a = new Object[n]; |
如果您真的对性能和空间感兴趣,并且知道您的数组只存储某些数字类型,那么您可以将dtype参数更改为其他一些值,如int。然后numpy将这些元素直接打包到数组中,而不是使数组引用int对象。
这样做:
1 2 3 4 5 6 | >>> 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]] |
其他解决方案将导致这种问题:
1 2 3 4 5 6 | >>> d = [ [ None ] * 2 ] * 2 >>> d [[None, None], [None, None]] >>> d[0][0] = 1 >>> d [[1, None], [1, None]] |
最好的办法是使用numpy库。
1 2 3 | from numpy import ndarray a = ndarray((5,),int) |
1 2 3 4 5 6 7 8 9 | >>> 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是一维数组。它们都是用零初始化的。
一个简单的解决方案是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | >>> 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] |
或者在列表中没有任何内容可以开始:
1 2 3 4 5 6 7 8 9 | >>> 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个迭代中:
1 2 3 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及所有后续:
1 2 3 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,1] |
我想通过发布一个示例程序及其输出来帮助您
程序:
1 2 3 4 5 6 7 8 9 10 11 12 | 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 |
输出:
1 2 3 | 2 [1, 2] [[1, 2], [1, 2]] |
我希望这能澄清你们关于他们声明的一些基本概念。用一些其他特定的值初始化它们,比如用
1 | x = [0]*10 |
希望它能帮上忙。!)
您可以尝试使用描述符来限制大小
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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 |
输出:
1 2 3 4 5 6 | [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] |
如果使用字节,则可以使用内置的
具体理解,
例如,如果您试图创建一个缓冲区,以便将文件内容读取到中,那么可以使用bytearray,如下所示(有更好的方法可以做到这一点,但示例是有效的):
1 2 3 | with open(FILENAME, 'rb') as f: data = bytearray(os.path.getsize(FILENAME)) f.readinto(data) |
在这段代码中,
我觉得很容易做的一件事就是设置一个数组例如,我喜欢的大小是空字符串
代码:
1 2 3 4 | import numpy as np x= np.zeros(5,str) print x |
输出:
1 | ['' '' '' '' ''] |
希望这是有帮助的:)