简体   繁体   English

如何在Python中就地对整数数组进行排序?

[英]How to sort an integer array in-place in Python?

how can one sort an integer array ( not a list) in-place in Python 2.6? 如何在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 : 好吧,你不能用array.array ,但你可以使用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: 或者你可以直接从array.array转换,如果你已经有:

a = array.array('i', [1, 3, 2])
a = numpy.array(a)

@steven mentioned numpy. @steven提到了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. numpy解决方案是要走的路。 However, I'll leave this up for reference. 但是,我会留下来参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM