【发布时间】:2011-02-06 02:24:12
【问题描述】:
我想在 python 中定义一个数组。我该怎么做?我必须使用列表吗?
【问题讨论】:
我想在 python 中定义一个数组。我该怎么做?我必须使用列表吗?
【问题讨论】:
列表更好,但你可以像这样使用数组:
array('l')
array('c', 'hello world')
array('u', u'hello \u2641')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.14])
更多信息there
【讨论】:
为什么要在列表上使用数组?这是一个comparison of the two,它清楚地说明了列表的优点。
【讨论】:
Python中有几种类型的数组,如果你想要一个经典的数组,那就用数组模块吧:
import array
a = array.array('i', [1,2,3])
但你也可以使用元组而不需要导入其他模块:
t = (4,5,6)
或列表:
l = [7,8,9]
元组使用起来效率更高,但它的大小是固定的,而您可以轻松地将新元素添加到列表中:
>>> l.append(10)
>>> l
[7, 8, 9, 10]
>>> t[1]
5
>>> l[1]
8
【讨论】:
如果您需要一个数组,因为您正在使用其他低级构造(例如在 C 中),您可以使用 ctypes。
import ctypes
UINT_ARRAY_30 = ctypes.c_uint*30 # create a type of array of uint, length 30
my_array = UINT_ARRAY_30()
my_array[0] = 1
my_array[3] == 0
【讨论】: