kbb*_*kbb 141 python arrays list
我想知道如何初始化一个数组(或列表),但要用值填充,以具有定义的大小.
例如在C中:
int x[5]; /* declared without adding elements*/
Run Code Online (Sandbox Code Playgroud)
我如何在python中做到这一点?
谢谢.
sam*_*ias 188
您可以使用:
>>> lst = [None] * 5
>>> lst
[None, None, None, None, None]
Run Code Online (Sandbox Code Playgroud)
Pat*_*rin 73
为什么这些问题没有得到明显答案的回答?
a = numpy.empty(n, dtype=object)
Run Code Online (Sandbox Code Playgroud)
这将创建一个长度为n的数组,可以存储对象.它无法调整大小或附加到.特别是,它不会通过填充其长度来浪费空间.这是Java的等价物
Object[] a = new Object[n];
Run Code Online (Sandbox Code Playgroud)
如果您真的对性能和空间感兴趣并且知道您的数组只存储某些数字类型,那么您可以将dtype参数更改为其他值,如int.然后numpy将这些元素直接打包到数组中,而不是使数组引用int对象.
TTi*_*imo 26
做这个:
>>> 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]]
Run Code Online (Sandbox Code Playgroud)
其他解决方案将导致这种问题:
>>> d = [ [ None ] * 2 ] * 2
>>> d
[[None, None], [None, None]]
>>> d[0][0] = 1
>>> d
[[1, None], [1, None]]
Run Code Online (Sandbox Code Playgroud)
laf*_*ras 12
最好的办法是使用numpy库.
from numpy import ndarray
a = ndarray((5,),int)
Run Code Online (Sandbox Code Playgroud)
一个简单的解决方案是x = [None]*length
,但请注意它将所有列表元素初始化为None
.如果尺寸确实是固定的,你也可以这样做x=[None,None,None,None,None]
.但严格地说,你不会得到未定义的元素,因为Python中不存在这种瘟疫.
>>> 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.])
Run Code Online (Sandbox Code Playgroud)
x是2-d阵列,y是1-d阵列.它们都用零初始化.
>>> 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]
Run Code Online (Sandbox Code Playgroud)
或者列表中没有任何内容可以开头:
>>> 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]
Run Code Online (Sandbox Code Playgroud)
在附加的第四次迭代:
>>> 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]
Run Code Online (Sandbox Code Playgroud)
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]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
422602 次 |
最近记录: |