Sorting a list of tuples with 3 elements in python

大兔子大兔子 提交于 2019-12-02 01:31:53
Martijn Pieters

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.

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