how can one sort an integer array (not a list) in-place in Python 2.6? Is there a suitable function in one of the standard libraries?
In other words, I'm looking for a function that would do something like this:
>>> a = array.array('i', [1, 3, 2])
>>> some_function(a)
>>> a
array('i', [1, 2, 3])
Thanks in advance!
Well, you can't do it with array.array
, but you can with numpy.array
:
In [3]: a = numpy.array([0,1,3,2], dtype=numpy.int)
In [4]: a.sort()
In [5]: a
Out[5]: array([0, 1, 2, 3])
Or you can convert directly from an array.array
if you have that already:
a = array.array('i', [1, 3, 2])
a = numpy.array(a)
@steven mentioned numpy.
Copies vs. in-place operation
-----------------------------
Most of the functions in `numpy` return a copy of the array argument
(e.g., `sort`). In-place versions of these functions are often
available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.
Exceptions to this rule are documented.
Looking at the array docs, I don't see a method for sorting. I think the following is about as close as you can get using standard functions, although it is really clobbering the old object with a new one with the same name:
import array
a = array.array('i', [1,3,2])
a = array.array('i', sorted(a))
Or, you could write your own.
With the extra information from the comments that you're maxing out memory, this seems inapplicable for your situation; the numpy solution is the way to go. However, I'll leave this up for reference.
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