Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:对一个列表进行排序,然后更改另一个列表_Python_List_Sorting - Fatal编程技术网

Python:对一个列表进行排序,然后更改另一个列表

Python:对一个列表进行排序,然后更改另一个列表,python,list,sorting,Python,List,Sorting,我有两个列表:一个包含一组x点,另一个包含y点。Python以某种方式将x点混合在一起,或者用户可以这样做。我需要按从低到高的顺序对它们进行排序,并移动y点以跟随它们的x对应项。它们在两个单独的列表中。。我该怎么做?您可以压缩列表并对结果进行排序。默认情况下,排序元组应在第一个成员上排序 >>> xs = [3,2,1] >>> ys = [1,2,3] >>> points = zip(xs,ys) >>> points

我有两个列表:一个包含一组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]

如果x和y是一个单位(比如一个点),那么将它们存储为元组比存储为两个单独的列表更有意义

无论如何,以下是您应该做的:

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

zipped_list = zip(x,y)
sorted_list = sorted(zipped_list)
如果可以使用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]

我会这样做,但是matplotlib使用类似的列表,或者,通过不使用两个单独的列表,而是保留元组列表来保持点的正确关联。阅读Mike Graham的答案。您还可以使用
zip
解压元组。如果您有大量项,您可能不想使用
zip(*排序(…)
。参数unpacking
*
不能像
zip(xs,ys)
那样高效,因为它必须传递尽可能多的参数,就像列表中有元组一样。最后两行可以安全地组合为
xs,ys=[v[sorted_index]for v in[xs,ys]
>>> 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]