在Python 2.6中如何排序整数数组(而不是列表)?在其中一个标准库中是否有适合的功能?如何在Python中就地对整数数组进行排序?
换句话说,我正在寻找的是会做一些这样的功能:提前
>>> a = array.array('i', [1, 3, 2])
>>> some_function(a)
>>> a
array('i', [1, 2, 3])
谢谢!
在Python 2.6中如何排序整数数组(而不是列表)?在其中一个标准库中是否有适合的功能?如何在Python中就地对整数数组进行排序?
换句话说,我正在寻找的是会做一些这样的功能:提前
>>> a = array.array('i', [1, 3, 2])
>>> some_function(a)
>>> a
array('i', [1, 2, 3])
谢谢!
好了,你不能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])
或者你也可以从array.array
,如果你有一个已经直接转换:
a = array.array('i', [1, 3, 2])
a = numpy.array(a)
这似乎是一个就地排序。好答案。 – 2011-04-04 15:24:35
太好了,非常感谢! – Bolo 2011-04-05 09:00:36
展望在array docs,我没有看到排序的方法。我认为以下是最接近你可以得到使用标准功能,虽然它确实重挫旧的对象有一个新的具有相同名称:
import array
a = array.array('i', [1,3,2])
a = array.array('i', sorted(a))
或者,你可以写你自己的。
从评论中提供的额外信息可以发现,这似乎不适用于您的情况; 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.
为什么你排除使用列表?你有没有简介,发现它缺乏?如果你必须使用一个数组并且需要排序,我建议使用numpy,它有一个数组排序方法。 – 2011-04-04 14:51:05
@Steven是的,我已经描绘过它。我正在研究几乎不适合RAM的整数大集合。整数列表至少比整数数组大3倍,所以我不能使用它们。您(或其他人)能否指出SciPy/NumPy中的相关功能? – Bolo 2011-04-04 14:59:16
从http://docs.scipy.org/doc/numpy/reference/routines.sort.html开始。请注意,默认排序返回一个副本,但是'ndarray.sort'就地排序。 (我没有使用SciPy/NumPy的经验,但是确实知道它很受尊重和高度优化。) – 2011-04-04 15:03:48