我有两个列表:一个包含一组x点,另一个包含y点。Python以某种方式将x点搞混了,或者用户可以。我需要按从低到高的顺序对它们进行排序,并将y点移动到它们的x对应位置。它们在两个单独的列表中..我该怎么做呢?
发布于 2010-04-29 04:42:22
您可以压缩列表并对结果进行排序。默认情况下,排序元组应该在第一个成员上排序。
>>> 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]
发布于 2010-04-29 04:51:17
>>> 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)
发布于 2010-04-29 20:53:17
>>> 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]
https://stackoverflow.com/questions/2732994
复制相似问题