Sort tuples based on second parameter
Question:
I have a list of tuples that look something like this:
("Person 1",10)
("Person 2",8)
("Person 3",12)
("Person 4",20)
What I want produced, is the list sorted in ascending order, by the second value of the tuple. So L[0] should be ("Person 2", 8)
after sorting.
How can I do this? Using Python 3.2.2 If that helps.
Answers:
You can use the key
parameter to list.sort()
:
my_list.sort(key=lambda x: x[1])
or, slightly faster,
my_list.sort(key=operator.itemgetter(1))
(As with any module, you’ll need to import operator
to be able to use it.)
def findMaxSales(listoftuples):
newlist = []
tuple = ()
for item in listoftuples:
movie = item[0]
value = (item[1])
tuple = value, movie
newlist += [tuple]
newlist.sort()
highest = newlist[-1]
result = highest[1]
return result
movieList = [("Finding Dory", 486), ("Captain America: Civil
War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529), ("The Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)]
print(findMaxSales(movieList))
output –> Rogue One
You may also apply the sorted
function on your list, which returns a new sorted list. This is just an addition to the answer that Sven Marnach has given above.
# using *sort method*
mylist.sort(key=lambda x: x[1])
# using *sorted function*
l = sorted(mylist, key=lambda x: x[1])
I have a list of tuples that look something like this:
("Person 1",10)
("Person 2",8)
("Person 3",12)
("Person 4",20)
What I want produced, is the list sorted in ascending order, by the second value of the tuple. So L[0] should be ("Person 2", 8)
after sorting.
How can I do this? Using Python 3.2.2 If that helps.
You can use the key
parameter to list.sort()
:
my_list.sort(key=lambda x: x[1])
or, slightly faster,
my_list.sort(key=operator.itemgetter(1))
(As with any module, you’ll need to import operator
to be able to use it.)
def findMaxSales(listoftuples):
newlist = []
tuple = ()
for item in listoftuples:
movie = item[0]
value = (item[1])
tuple = value, movie
newlist += [tuple]
newlist.sort()
highest = newlist[-1]
result = highest[1]
return result
movieList = [("Finding Dory", 486), ("Captain America: Civil
War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529), ("The Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)]
print(findMaxSales(movieList))
output –> Rogue One
You may also apply the sorted
function on your list, which returns a new sorted list. This is just an addition to the answer that Sven Marnach has given above.
# using *sort method*
mylist.sort(key=lambda x: x[1])
# using *sorted function*
l = sorted(mylist, key=lambda x: x[1])