How to sort a tuple based on a value within the list of tuples

允我心安 提交于 2021-01-28 16:42:28

问题


In python, I wish to sort tuples based on the value of their last element. For example, i have a tuple like the one below.

tuples = [(2,3),(5,7),(4,3,1),(6,3,5),(6,2),(8,9)]

which after sort I wish to be in this format.

tuples = [(4,3,1),(6,2),(2,3),(6,3,5),(5,7),(8,9)]

How do i get to doing that?


回答1:


Povide list.sort with an appropriate key function that returns the last element of a tuple:

tuples.sort(key=lambda x: x[-1])



回答2:


You can use:

from operator import itemgetter

tuples = sorted(tuples, key=itemgetter(-1))

The point is that we use key as a function to map the elements on an orderable value we wish to sort on. With itemgetter(-1) we construct a function, that for a value x, will return x[-1], so the last element.

This produces:

>>> sorted(tuples, key=itemgetter(-1))
[(4, 3, 1), (6, 2), (2, 3), (6, 3, 5), (5, 7), (8, 9)]


来源:https://stackoverflow.com/questions/48205443/how-to-sort-a-tuple-based-on-a-value-within-the-list-of-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!