Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我想通过 Python 中的某个表达式对列表列表进行排序。
即,按 的值对列表列表进行排序abs(x[0] - x[3]),其中x是子列表。我可以通过将另一个元素附加到列表中,按它排序并删除它来做到这一点,但这似乎效率低下。有没有更好的办法?
abs(x[0] - x[3])
x
只需将其作为排序的关键函数传递:
my_list.sort(key=lambda x: abs(x[0] - x[3]))
例如:
In [1]: my_list = [[1, 2], [3, 7], [4, 6]] In [2]: my_list.sort(key=lambda x: abs(x[0] - x[1])) In [3]: my_list Out[3]: [[1, 2], [4, 6], [3, 7]]