Ordered list question
jyoung79 at kc.rr.com
jyoung79 at kc.rr.com
Sun Jul 17 12:28:44 EDT 2011
I'm currently working on a project where I'm looping through xml elements,
pulling the 'id' attribute (which will be coerced to a number) as well as the
element tag. I'm needing these elements in numerical order (from the id).
Example xml might look like:
<price id="5">
<copyright id="1">
<address id="3">
There will be cases where elements might be excluded, but I'd still need to
put what I find in id numerical order. In the above example I would need
the order of 1, 3, 5 (or copyright, address, price). In javascript I can easily
index an array, and any preceding elements that don't exist will be set to
'undefined':
-----
var a = [];
a[parseInt('5')] = 'price';
a[parseInt('1')] = 'copyright';
a[parseInt('3')] = 'address';
// a is now [undefined, copyright, undefined, address, undefined, price]
-----
Next, I can loop through the array and remove every 'undefined' in order to
get the ordered array I need:
-----
> var newA = [];
> for (var x = 0; x < a.length; x++) {
if (a[x] != undefined) {
newA.push(a[x]);
}
}
// newA is now [copyright, address, price]
-----
My question is, does python have a similar way to do something like this?
I'm assuming the best way is to create a dictionary and then sort it by
the keys?
Thanks.
Jay
More information about the Python-list
mailing list