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.
问题:
回答1:
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')
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]
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
回答2:
In python, A dynamic array is an 'array' from the array module. E.g.
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
This datatype is essentially a cross between the built-in 'list' type and the numpy 'ndarray' type. Like an ndarray, elements in arrays are C types, specified at initialization. They are not pointers to python objects; this may help avoid some misuse and semantic errors, and modestly improves performance.
However, this datatype has essentially the same methods as a python list, barring a few string & file conversion methods. It lacks all the extra numerical functionality of an ndarray.
See https://docs.python.org/2/library/array.html for details.
回答3:
Here's a great method I recently found on a different stack overflow post regarding multi-dimensional arrays, but the answer works beautifully for single dimensional arrays as well:
# 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 ) ]
I love this because you can specify the contents and size dynamically, in one line!
One more for the road:
# Dynamic content initialization:
MyFunkyArray = [ x * a + b for x in range ( n ) ]