Possible Duplicate:
Python: sort a part of a list, in place
I want to implement a decision tree algorithm, and my implementation calls for sorting the table in order attribute by attribute, in place.
Here is the gist of it: choose an attribute, sort over it. All entries in the table that share that attribute can now be thought of as another list, because permuting within them does not modify that attribute.
So then, how can I sort just that relevant subportion? Do I need to write my own wrapper around the list with a specified base and length?
int * ptr = array; std::sort( ptr + 1, ptr + 4 );
Method #1 : Using count() + set() + sorted() The sorted function can be used to sort the elements as desired, the frequency can be computed using the count function and removal of duplicates can be handled using the set function.
Approach : Zip the two lists. Create a new, sorted list based on the zip using sorted(). Using a list comprehension extract the first elements of each pair from the sorted, zipped list.
This is sort-of inplace. It does require temporary storage for the sorted part
>>> a=range(20,0,-1)
>>> a
[20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> a[10:15]=sorted(a[10:15])
>>> a
[20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 6, 7, 8, 9, 10, 5, 4, 3, 2, 1]
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With