how do you sort a list of list of tuples in python
for example: Note that the last elements of the tuples are same
a = [
[(1, 5, 6), (2, 2, 6), (3, 6, 6)],
[(6, 1, 3), (5, 7, 3), (4, 1, 3)],
[(5, 7, 2), (7, 5, 2), (6, 3, 2)],
[(9, 1, 7), (1, 5, 7), (2, 6, 7)]
]
I want to sort using the last element of the tuple as the key. So the expected result is
[
[(5, 7, 2), (7, 5, 2), (6, 3, 2)],
[(6, 1, 3), (5, 7, 3), (4, 1, 3)],
[(1, 5, 6), (2, 2, 6), (3, 6, 6)],
[(9, 1, 7), (1, 5, 7), (2, 6, 7)]
]
In [27]: a = [
....:
....: [(1, 5, 6), (2, 2, 6), (3, 6, 6)],
....: [(6, 1, 3), (5, 7, 3), (4, 1, 3)],
....: [(5, 7, 2), (7, 5, 2), (6, 3, 2)],
....: [(9, 1, 7), (1, 5, 7), (2, 6, 7)]
....:
....: ]
# any tuple (first will do), last element
In [28]: a.sort(key=lambda l: l[0][-1])
In [29]: a
Out[29]:
[[(5, 7, 2), (7, 5, 2), (6, 3, 2)],
[(6, 1, 3), (5, 7, 3), (4, 1, 3)],
[(1, 5, 6), (2, 2, 6), (3, 6, 6)],
[(9, 1, 7), (1, 5, 7), (2, 6, 7)]]
Use the key
argument to sort and a lambda
function
a.sort(key=lambda x: x[-1][-1]). # sorts in-place
sorted(a, key=lambda x: x[-1][-1]). # new sorted list
Edit : change the first index depending on what tuple you want to look at for the comparison. Ie, use x[0][-1]
to compare based on the first tuple
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.