如何在Python中声明数组?


当前回答

计算时,使用numpy数组:

import numpy as np

a = np.ones((3,2))        # a 2D array with 3 rows, 2 columns, filled with ones
b = np.array([1,2,3])     # a 1D array initialised using a list [1,2,3]
c = np.linspace(2,3,100)  # an array with 100 points beteen (and including) 2 and 3

print(a*1.5)  # all elements of a times 1.5
print(a.T+b)  # b added to the transpose of a

这些numpy数组可以从磁盘保存和加载(甚至压缩),具有大量元素的复杂计算像c一样快。

多用于科学环境。更多信息请看这里。

其他回答

你不需要在Python中声明任何东西。你只需使用它。我建议你从http://diveintopython.net开始。

是这样的:

my_array = [1, 'rebecca', 'allard', 15]

我有一个字符串数组,需要一个具有相同长度的布尔值的数组,初始化为True。这就是我所做的

strs = ["Hi","Bye"] 
bools = [ True for s in strs ]
# This creates a list of 5000 zeros
a = [0] * 5000  

您可以像使用数组一样,使用[n]符号读取和写入此列表中的任何元素。

它似乎具有与数组相同的随机访问性能。我不能说它如何分配内存,因为它还支持不同类型的混合,包括字符串和对象,如果你需要的话。

Python称它们为列表。你可以用方括号和逗号写一个列表文字:

>>> [6,28,496,8128]
[6, 28, 496, 8128]