2010-04-28 73 views

回答

17

您可以壓縮列表並對結果進行排序。排序元組時,默認情況下,應該排序第一個成員。

>>> xs = [3,2,1] 
>>> ys = [1,2,3] 
>>> points = zip(xs,ys) 
>>> points 
[(3, 1), (2, 2), (1, 3)] 
>>> sorted(points) 
[(1, 3), (2, 2), (3, 1)] 

然後再解壓它們:

>>> sorted_points = sorted(points) 
>>> new_xs = [point[0] for point in sorted_points] 
>>> new_ys = [point[1] for point in sorted_points] 
>>> new_xs 
[1, 2, 3] 
>>> new_ys 
[3, 2, 1] 
+0

謝謝!棒極了! – 2010-04-28 20:54:03

+2

或者,通過沒有兩個單獨的列表來保持點正確關聯,但保留元組列表。 – 2010-04-28 21:04:42

+1

閱讀Mike Graham的回答。你也可以使用'zip'來解開元組。 – 2010-04-28 21:10:11

4

如果x和y的意思是一個單元(如一個點),它將使更多的意義將它們存儲爲元組而不是兩個單獨的列表。

無論如何,這裏是你應該做的:

x = [4, 2, 5, 4, 5,…] 
y = [4, 5, 2, 3, 1,…] 

zipped_list = zip(x,y) 
sorted_list = sorted(zipped_list) 
+1

我會這樣做,但matplotlib使用這樣的列表 – 2010-04-28 20:55:09

16
>>> xs = [5, 2, 1, 4, 6, 3] 
>>> ys = [1, 2, 3, 4, 5, 6] 
>>> xs, ys = zip(*sorted(zip(xs, ys))) 
>>> xs 
(1, 2, 3, 4, 5, 6) 
>>> ys 
(3, 2, 6, 4, 1, 5) 
+4

如果你有大量的項目,你可能不想使用'zip(* sorted(...))'。參數拆包'*'不能像'zip(xs,ys)'那樣有效地完成任務,因爲它必須傳遞與列表中的元組相同數量的參數。 – 2010-04-28 21:13:29

10
>>> import numpy 

>>> sorted_index = numpy.argsort(xs) 
>>> xs = [xs[i] for i in sorted_index] 
>>> ys = [ys[i] for i in sorted_index] 

如果你能numpy.array工作

>>> xs = numpy.array([3,2,1]) 
>>> xs = numpy.array([1,2,3]) 
>>> sorted_index = numpy.argsort(xs) 
>>> xs = xs[sorted_index] 
>>> ys = ys[sorted_index] 
+0

最後兩行可以安全地組合爲'xs,ys = [v [sorted_index] for v in [xs,ys]]'? – 2017-11-12 15:00:45

相關問題