For fixing the code above, you can simply try following:
def ranked_games(L):
L.sort(key = lambda x:x[1], reverse=True) #sort by value
print("Sorted by Value Descending", [i for i, _ in L[:10]]) # [:10] for slicing 10 sorted values
# calling the function
my_list = [('abc',10),('def',15),('ghi',10),('abc', 12),('xyz',100)]
ranked_games(my_list)
print('Original List: ', my_list)
Result:
Sorted by Value Descending ['xyz', 'def', 'abc', 'abc', 'ghi']
Original List: [('xyz', 100), ('def', 15), ('abc', 12), ('abc', 10), ('ghi', 10)]
Note that the original list is also sorted since .sort
method of list is called. If you do not want the original list to be sorted then you may want to call sorted
function and pass in list as a parameter as below:
def ranked_games(L):
sorted_list = sorted(L, key = lambda x:x[1], reverse=True) #sort by value
print("Sorted by Value Descending",[i for i, _ in sorted_list[:10]]) # [:10] for slicing 10 sorted values
# calling the function
my_list = [('abc',10),('def',15),('ghi',10),('abc', 12),('xyz',100)]
ranked_games(my_list)
print('Original List: ', my_list)
Result:
Sorted by Value Descending ['xyz', 'def', 'abc', 'abc', 'ghi']
Original List: [('abc', 10), ('def', 15), ('ghi', 10), ('abc', 12), ('xyz', 100)]
For more about difference between sort
and sorted
, you can look at relevant question What is the difference between sorted(list)
vs list.sort()
?.