我基本上想要 C 中这个数组的 Python 等价物:
int a[x];
但是在python中我声明了一个数组,如:
a = []
问题是我想为随机插槽分配如下值:
a[4] = 1
但我不能用 Python 做到这一点,因为 Python 列表是空的(长度为 0)。
我基本上想要 C 中这个数组的 Python 等价物:
int a[x];
但是在python中我声明了一个数组,如:
a = []
问题是我想为随机插槽分配如下值:
a[4] = 1
但我不能用 Python 做到这一点,因为 Python 列表是空的(长度为 0)。
如果“数组”实际上是指 Python 列表,则可以使用
a = [0] * 10
或者
a = [None] * 10
你不能在 Python 中做你想做的事(如果我没看错的话)。您需要为列表的每个元素(或您所说的数组)输入值。
但是,试试这个:
a = [0 for x in range(N)] # N = size of list you want
a[i] = 5 # as long as i < N, you're okay
对于其他类型的列表,使用 0 以外 None
的值通常也是一个不错的选择。
您可以使用 numpy:
import numpy as np
空数组示例:
np.empty([2, 2])
array([[ -9.74499359e+001, 6.69583040e-309],
[ 2.13182611e-314, 3.06959433e-309]])
您也可以使用列表的扩展方法对其进行扩展。
a= []
a.extend([None]*10)
a.extend([None]*20)
只需声明列表并附加每个元素。例如:
a = []
a.append('first item')
a.append('second item')
如果您(或此问题的其他搜索者)实际上有兴趣创建一个连续数组来填充整数,请考虑bytearray和memoryivew:
# cast() is available starting Python 3.3
size = 10**6
ints = memoryview(bytearray(size)).cast('i')
ints.contiguous, ints.itemsize, ints.shape
# (True, 4, (250000,))
ints[0]
# 0
ints[0] = 16
ints[0]
# 16
x=[]
for i in range(0,5):
x.append(i)
print(x[i])
也可以创建一个具有一定大小的空数组:
array = [[] for _ in range(n)] # n equal to your desired size
array[0].append(5) # it appends 5 to an empty list, then array[0] is [5]
如果您将其定义为array = [] * n
then 如果您修改一个项目,则所有项目都以相同的方式更改,因为它的可变性。
如果你真的想要一个 C 风格的数组
import array
a = array.array('i', x * [0])
a[3] = 5
try:
[5] = 'a'
except TypeError:
print('integers only allowed')
请注意, python 中没有未初始化变量的概念。变量是绑定到值的名称,因此该值必须具有某些内容。在上面的示例中,数组初始化为零。
然而,这在 python 中并不常见,除非你真的需要它来处理低级的东西。在大多数情况下,您最好使用空列表或空 numpy 数组,正如其他答案所建议的那样。
分配“随机插槽”的(我认为唯一的)方法是使用字典,例如:
a = {} # initialize empty dictionary
a[4] = 1 # define the entry for index 4 to be equal to 1
a['French','red'] = 'rouge' # the entry for index (French,red) is "rouge".
这对于“快速破解”很方便,如果您没有对数组元素的密集访问权限,则查找开销是无关紧要的。否则,使用固定大小的预分配(例如,numpy)数组会更有效,您可以使用a = np.empty(10)
(对于长度为 10 的未初始化向量)或a = np.zeros([5,5])
使用零初始化的 5x5 矩阵创建该数组。
备注:在您的 C 示例中,您还必须int a[x];
在分配(不是这样)“随机槽”(即 0 和 x-1 之间的整数索引)之前分配数组(您的)。
参考:
dict
数据类型:https : //docs.python.org/3/library/stdtypes.html#mapping-types-dict