python - 在 Python 中,我如何声明一个动态数组

标签 python listbox

我想声明一个数组,并且应该删除 ListBox 中存在的所有项目,而不管 ListBox 中存在的组名称如何。任何人都可以帮助我用 Python 编码。我正在使用 WINXP 操作系统和 Python 2.6。

最佳答案

在 Python 中,list 是一个动态数组。您可以像这样创建一个:

lst = [] # Declares an empty list named lst

或者你可以用元素填充它:

lst = [1,2,3]

您可以使用“追加”添加项目:

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

关于python - 在 Python 中,我如何声明一个动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2910864/

相关文章:

c# - 将项目从一个列表框移动到另一个列表框

c# - 包含超过 100 个项目的列表框崩溃

python - 设置 Huey 以将 Redis 与 Flask 一起使用

python - 从文件生成字符串

python - 将字符串和字符串列表组合成一个大列表

c# - 在堆栈面板中滚动列表框?

Python:创建文本文件,写入,替换字符串

Python boto3 SNS 电子邮件格式(每个字符串换行)

list - 在 Windows phone 7 中更改 ListBox 的选定项

c# - WPF - 扩展器中的滚动列表框