Hi all I have a list of tuple like this:
L = [(el,3,1),(el2,2,3),(el3,3,2),(el4,2,4),(el5,1,3)]
and I would like to order it like this:
L_ordered = [(el5,1,3),(el2,2,3),(el4,2,4),(el,3,1),(el3,3,2)]
I am ordering first with respect to second number and then with respect to the third number but maintaining the order with respect to the second one. Someone know how to do that in python?
Use the key
argument of the sort()
or sorted()
function; have it return a tuple of the fields that should be considered, in the order they should be considered:
L = [(el,3,1), (el2,2,3), (el3,3,2), (el4,2,4), (el5,1,3)]
L_ordered = sorted(L, key=lambda item: (item[1], item[2]))
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.