我想声明一个数组,并且无论ListBox中存在的组名如何,都应删除ListBox中存在的所有项.任何人都可以帮我编写Python代码.我正在使用WINXP OS和Python 2.6.
Mic*_*yan 81
在Python中,a list是动态数组.您可以创建一个这样的:
lst = [] # Declares an empty list named lst
Run Code Online (Sandbox Code Playgroud)
或者你可以填写项目:
lst = [1,2,3]
Run Code Online (Sandbox Code Playgroud)
您可以使用"追加"添加项目:
lst.append('a')
Run Code Online (Sandbox Code Playgroud)
您可以使用循环遍历列表的元素for:
for item in lst:
# Do something with item
Run Code Online (Sandbox Code Playgroud)
或者,如果您想跟踪当前索引:
for idx, item in enumerate(lst):
# idx is the current idx, while item is lst[idx]
Run Code Online (Sandbox Code Playgroud)
要删除元素,可以使用del命令或remove函数,如:
del lst[0] # Deletes the first item
lst.remove(x) # Removes the first occurence of x in the list
Run Code Online (Sandbox Code Playgroud)
但请注意,不能迭代列表并同时修改它; 要做到这一点,你应该迭代一下列表(基本上是列表的副本).如:
for item in lst[:]: # Notice the [:] which makes a slice
# Now we can modify lst, since we are iterating over a copy of it
Run Code Online (Sandbox Code Playgroud)
小智 6
这是我最近在关于多维数组的不同堆栈溢出帖子上发现的一个很棒的方法,但答案对于单维数组也很有效:
# 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 ) ]
Run Code Online (Sandbox Code Playgroud)
我喜欢这个,因为您可以在一行中动态指定内容和大小!
路上还有一张:
# Dynamic content initialization:
MyFunkyArray = [ x * a + b for x in range ( n ) ]
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
此数据类型本质上是内置“列表”类型和numpy“ ndarray”类型之间的交叉。像ndarray一样,数组中的元素是C类型,在初始化时指定。它们不是指向python对象的指针。这可以帮助避免一些误用和语义错误,并适度提高性能。
但是,此数据类型具有与python列表基本相同的方法,除了一些字符串和文件转换方法。它缺少ndarray的所有其他数值功能。
有关详细信息,请参见https://docs.python.org/2/library/array.html。