How to sort an integer array in-place in Python?

ε祈祈猫儿з 提交于 2020-01-22 14:57:08

问题


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!


回答1:


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)



回答2:


@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.



回答3:


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.



来源:https://stackoverflow.com/questions/5540148/how-to-sort-an-integer-array-in-place-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!