在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