Python:对列表进行排序并因此更改另一个列表

Gab*_*lli 16 python sorting list

我有两个列表:一个包含一组x点,另一个包含y个点.Python以某种方式设法混合x点,或者用户可以.我需要按从最低到最高的顺序对它们进行排序,然后移动y点以跟随它们的x对应项.它们分为两个单独的列表..我该怎么办?

dan*_*ben 18

您可以压缩列表并对结果进行排序.默认情况下,排序元组应该对第一个成员进行排序.

>>> 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)]
Run Code Online (Sandbox Code Playgroud)

然后再打开它们:

>>> 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]
Run Code Online (Sandbox Code Playgroud)

  • 或者,通过没有两个单独的列表来保持点正确关联,但保留元组列表. (2认同)

Mik*_*ham 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)
Run Code Online (Sandbox Code Playgroud)

  • 如果你有大量的项目,你可能不想使用`zip(*sorted(...))`.参数解包`*`不能像`zip(xs,ys)`那样有效,因为它必须传递与列表中的元组一样多的参数. (5认同)

rem*_*osu 10

>>> import numpy

>>> sorted_index = numpy.argsort(xs)
>>> xs = [xs[i] for i in sorted_index]
>>> ys = [ys[i] for i in sorted_index]
Run Code Online (Sandbox Code Playgroud)

如果你可以使用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]
Run Code Online (Sandbox Code Playgroud)