我有两个列表:一个包含一组x点,另一个包含y点。Python 有时会混淆 x 点,或者用户可能会混淆。我需要将它们按最低到最高的顺序排序,并移动 y 点以跟随它们的 x 对应项。它们在两个单独的列表中。我该怎么做?
您可以压缩列表并对结果进行排序。默认情况下,对元组进行排序应该是按第一个成员排序的。
>>> 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]
>>> 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)
zip(*sorted(...))
。参数解包的*
不能像zip(xs, ys)
一样高效地工作,因为它必须传递与列表中元组数量相同的参数。 - Thomas Wouters>>> 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]
xs,ys=[v[sorted_index] for v in [xs,ys]]
吗? - Itamar Katzx = [4, 2, 5, 4, 5,…]
y = [4, 5, 2, 3, 1,…]
zipped_list = zip(x,y)
sorted_list = sorted(zipped_list)
zip
来解压元组。 - Gary Kerr