Reputation: 33
I want to rank this list of tuples:
[("Blueberries", 1), ("Strawberries", 2), ("Apple", 3), ("Apple", 4), ("Orange", 2)]
It should output:
[("Apple", 4), ("Apple", 3), ("Strawberries", 2), ("Orange", 2), ("Blueberries", 1)]
A dictionary works great without duplicate values. Is there any other way I could approach this? Or is there a way I could do this with a dictionary? I'm completely lost.
Upvotes: 1
Views: 68
Reputation: 3113
You can sort a list using the key=
parameter to define which function you want to use for the sort. In this case, it looks like you want to sort based off of the second item in the tuple, so:
l = [("Blueberries", 1), ("Strawberries", 2), ("Apple", 3), ("Apple", 4), ("Orange", 2)]
sorted_list = sorted(l,key=lambda x: x[1], reverse=True)
You can do this without using a lambda function by just defining that function with a name.
def my_sort_func(item):
return item[1]
sorted_list = sorted(l, key=my_sort_func, reverse=True)
Upvotes: 1