Python:对列表进行排序,然后更改另一个列表 [英] Python: sort a list and change another one consequently

查看:169
本文介绍了Python:对列表进行排序,然后更改另一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表:一个包含一组x点,另一个包含y点. Python设法以某种方式将x点混合在一起,或者用户可以这样做.我需要按照从最低到最高的顺序对它们进行排序,并移动y点以跟随其x对应对象.它们在两个单独的列表中.我该怎么办?

I have two lists: one contains a set of x points, the other contains y points. Python somehow manages to mix the x points up, or the user could. I'd need to sort them by lowest to highest, and move the y points to follow their x correspondants. They are in two separate lists.. how do I do it?

推荐答案

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

You could zip the lists and sort the result. Sorting tuples should, by default, sort on the first member.

>>> 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)]

然后再次打开它们的包装:

And then to unpack them again:

>>> 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]

这篇关于Python:对列表进行排序,然后更改另一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆