Sorted by two values

Question:

I have a list of lists:

l = [
    ["I", 2, 3],
    ["You" 3, 2],
]

How can i sort that in terms of max second element and min of third?

Asked By: Zero

||

Answers:

I think there is a typo in your list. If it is:

l = [["I",2,3],["You",3,2]]

you can do the following:

l.sort(key = lambda lst:(-lst[1],lst[2]))
Answered By: Lumin
l = [
    ["I", 2, 3],
    ["You", 3, 2]
]

# The sorted() function returns a sorted list of the specified iterable object.
l = sorted(l, key=lambda x: x[1], reverse=True) # False will sort ascending, True will sort descending. Default is False.
l = sorted(l, key=lambda x: x[2])

print(l)
Answered By: Luka Banfi

This question may be of use to you How do I get the last element of a list?

l = [['I', '2', '3'],['You' '3', '2']]

first_item = l[0][0]
last_item = l[-1][-1]

this is how you would access the very first element and very last element in a nested list. I am not sure what you mean by "sort that in terms of max second element and min of third?"

Answered By: Skynet
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.