Sorting a list of tuples with 3 elements in python

為{幸葍}努か 提交于 2019-12-02 03:08:11

问题


I have a list of some tuples. Each tuple has three elements. I need to sort the list. To break tie between two tuples, first element of tuple is looked then if still tied then the second element. List is like below.

L = [(1, 14, 0), (14, 1, 1), (1, 14, 2), (14, 2, 3), (2, 4, 4), (4, 11, 5), (11, -1000, 6)]

In C the sort function takes a compare function and that does everything simply. But I couldn't figure it out after trying for sometimes in python. Can anybody help me?


回答1:


Just sort the list; the default sort does just what you want.

When comparing two tuples, they are ordered according to their contents; sorted on the first element first, then if they are equal, sorted on the second element, etc.

Demo:

>>> L = [(14, 2, 3), (1, 14, 0), (14, 1, 1), (1, 14, 2), (2, 4, 4), (4, 11, 5), (11, -1000, 6)]
>>> sorted(L)
[(1, 14, 0), (1, 14, 2), (2, 4, 4), (4, 11, 5), (11, -1000, 6), (14, 1, 1), (14, 2, 3)]

I moved the (14, 2, 3) element forward to show that it is still sorted after (14, 1, 1).

Python's list.sort() method and sorted() function take a key function that returns a value on which to sort instead if you need a different sort order. If you wanted to sort on the last element first, then second last, etc. for example, you'd use:

sorted(L, key=lambda t: t[::-1])

where the lambda returns a reversed tuple to sort on instead. The callable object you pass to key is called for each element in the input sequence to 'augment' the list before sorting, as if you had done:

[s[1] for s in sorted((key(s), s) for s in L)]

The t[::-1] uses a reversing slice.

For more detail, see the Python Sorting HOWTO.



来源:https://stackoverflow.com/questions/18374585/sorting-a-list-of-tuples-with-3-elements-in-python

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