[Tutor] arrays
John Fouhy
john at fouhy.net
Fri Sep 15 02:55:21 CEST 2006
On 15/09/06, federico ramirez <fedekiller at gmail.com> wrote:
> an array to order the keys and then display it in order but..python orders
> the array like this
>
> ['_1', '_10', '_11', '_12', '_13', '_2', '_3', '_4', '_5', '_6', '_7', '_8',
> '_9']
>
> and i want
>
> ['_1', '_2', '_3', '_4', '_5', '_6', '_7', '_8', '_9','_10', '_11', '_12',
> '_13']
Hi,
First, just a terminology note -- in python, these are called lists, not arrays.
> arr = []
> for key in db.keys():
> arr += [key]
> arr.sort()
> arr.reverse()
db.keys() returns a _new_ list, so there is no need to do this step;
you could just write:
arr = db.keys()
Now, since your keys are strings, python is sorting them
lexicographically, which is why (for instance) '_10' comes before
'_2'. You need to tell python to change its sort order.
You can do this in a couple of ways. If you have python2.4 or
greater, you can use the key= keyword argument to sort, like this:
def keyToInt(s):
"""Convert '_10' to 10, '_2' to 2, etc. """
return int(s[1:])
arr.sort(key=keyToInt)
If you have an earlier version of python, you can define your own
comparison function:
def myCmp(x, y):
return cmp(keyToInt(x), keyToInt(y))
arr.sort(myCmp)
You can also use the decorate-sort-undecorate idiom, which may be
faster than a custom comparison function if the list is very large.
decorated = [(keyToInt(s), s) for s in arr]
decorated.sort()
arr = [x[1] for x in decorated]
> for i in range(len(db)):
> print db[arr[i]],'<br />'
In python, you can iterate over lists directly. ie, since arr is your
list of keys:
for key in arr:
print db[key], '<br />'
HTH!
--
John.
More information about the Tutor
mailing list