Python:排序一个列表并相应地改变另一个列表
我有两个列表:一个是一些x坐标,另一个是y坐标。Python有时候会把这些x坐标搞混,或者用户也可能搞混。我需要把这些x坐标从小到大排序,然后把对应的y坐标也跟着它们一起移动。因为它们在两个不同的列表里,我该怎么做呢?
4 个回答
10
>>> import numpy
>>> sorted_index = numpy.argsort(xs)
>>> xs = [xs[i] for i in sorted_index]
>>> ys = [ys[i] for i in sorted_index]
>>> 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]
如果你能使用 numpy.array
16
在编程中,有时候我们会遇到一些问题,特别是在使用某些工具或者库的时候。这些问题可能会让我们感到困惑,不知道该怎么解决。比如,有人可能在使用一个特定的功能时,发现它没有按照预期工作,或者出现了错误信息。
这时候,我们可以去一些技术论坛,比如StackOverflow,去寻找答案。在这些论坛上,很多人会分享他们的经验和解决方案,帮助其他人解决类似的问题。
总之,遇到问题时,不要着急,可以寻求社区的帮助,通常会找到有用的建议和解决办法。
>>> 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)
19
你可以把这些列表压缩在一起,然后对结果进行排序。默认情况下,排序元组时会根据第一个元素进行排序。
>>> 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]