在Python中如何声明动态数组
我想声明一个数组,并且想把列表框中所有的项目都删除,不管它们的组名是什么。有没有人能帮我写一下Python代码?我使用的是WINXP操作系统和Python 2.6。
5 个回答
6
我最近在一个关于多维数组的不同的Stack Overflow帖子上发现了一个很棒的方法,这个方法对一维数组也非常有效:
# Create an 8 x 5 matrix of 0's:
w, h = 8, 5;
MyMatrix = [ [0 for x in range( w )] for y in range( h ) ]
# Create an array of objects:
MyList = [ {} for x in range( n ) ]
我喜欢这个方法,因为你可以在一行代码中动态地指定内容和大小!
再来一个例子:
# Dynamic content initialization:
MyFunkyArray = [ x * a + b for x in range ( n ) ]
10
在Python中,动态数组是来自数组模块的一种“数组”。例如:
from array import array
x = array('d') #'d' denotes an array of type double
x.append(1.1)
x.append(2.2)
x.pop() # returns 2.2
这种数据类型其实是Python内置的“列表”类型和numpy的“ndarray”类型的结合体。和ndarray一样,数组中的元素是C语言的类型,这些类型在初始化时就确定了。它们不是指向Python对象的指针;这样可以帮助避免一些误用和语义错误,并且适度提高了性能。
不过,这种数据类型的基本方法和Python列表是一样的,除了几个字符串和文件转换的方法。它没有ndarray的额外数值功能。
想了解更多细节,可以查看https://docs.python.org/2/library/array.html。
104
在Python中,list
(列表)是一种动态数组。你可以这样创建一个列表:
lst = [] # Declares an empty list named lst
或者你可以给它添加一些内容:
lst = [1,2,3]
你可以用“append”来添加新项目:
lst.append('a')
你可以使用for
循环来遍历列表中的每个元素:
for item in lst:
# Do something with item
如果你想要记录当前的索引位置,可以这样做:
for idx, item in enumerate(lst):
# idx is the current idx, while item is lst[idx]
要删除元素,你可以使用del命令或者remove函数,如下所示:
del lst[0] # Deletes the first item
lst.remove(x) # Removes the first occurence of x in the list
不过要注意,不能在遍历列表的同时修改它;如果想要这样做,你应该遍历列表的一部分(这基本上是列表的一个副本)。可以这样做:
for item in lst[:]: # Notice the [:] which makes a slice
# Now we can modify lst, since we are iterating over a copy of it