I have gotten python to read a file and add the content into a list ('batman, 10', 'Iphone,900') but can't figure out how to make it sort it out so batman, 10 will be first as its number is lower and not because of its name. How can I do this?
Asked
Active
Viewed 41 times
1 Answers
0
you want a special key which splits the string, converts the second part to integer to pass to sort
the_tuple = ('batman, 10', 'Iphone,900')
result = sorted(the_tuple, key = lambda x : int(x.split(",")[1]))
You can add a tiebreaker if needed in case of a same number/different name. In that case I'd avoid lambda
as it makes split
repeat:
the_tuple = ('robin, 10', 'batman, 10', 'Iphone,900')
def sort_function(x):
name,number = x.split(",")
return int(number),name
result = sorted(the_tuple, key = sort_function)
result:
['batman, 10', 'robin, 10', 'Iphone,900']
to sort by biggest number, just add reverse=True
to sort
(that also reverses the tiebreaker so another option is to do return -int(number),name
(negate the number)

Jean-François Fabre
- 137,073
- 23
- 153
- 219