在Python中如何声明动态数组 [英] In Python How can I declare a Dynamic Array

查看:306
本文介绍了在Python中如何声明动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要声明一个Array,并且无论ListBox中存在的Group名称如何,ListBox中存在的所有项目都应删除.任何机构都可以帮助我使用Python进行编码.我正在使用WINXP OS& Python 2.6.

I want to declare an Array and all items present in the ListBox Should Be deleted irrespective of the Group name present in the ListBox. can any body help me coding in Python. I am using WINXP OS & Python 2.6.

推荐答案

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

In Python, a list is a dynamic array. You can create one like this:

lst = [] # Declares an empty list named lst

或者您可以在其中填充项目:

Or you can fill it with items:

lst = [1,2,3]

您可以使用添加"添加项目:

You can add items using "append":

lst.append('a')

您可以使用for循环遍历列表的元素:

You can iterate over elements of the list using the for loop:

for item in lst:
    # Do something with item

或者,如果您想跟踪当前索引:

Or, if you'd like to keep track of the current index:

for idx, item in enumerate(lst):
    # idx is the current idx, while item is lst[idx]

要删除元素,可以使用del命令或remove函数,如下所示:

To remove elements, you can use the del command or the remove function as in:

del lst[0] # Deletes the first item
lst.remove(x) # Removes the first occurence of x in the list

但是,请注意,不能迭代列表并同时对其进行修改;为此,您应该改为遍历列表的一部分(基本上是列表的副本).如:

Note, though, that one cannot iterate over the list and modify it at the same time; to do that, you should instead iterate over a slice of the list (which is basically a copy of the list). As in:

 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中如何声明动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆