Sorting Tuples In a list by alphabetical order and it's value - Python -
this question has answer here:
- how sort (list/tuple) of lists/tuples? 10 answers
i creating program sorts test results alphabetical value (name) - highest lowest (score). have created list scores appended to. here code:
scores=[] quits='' while quits!= 'y': name=input("what's name? ") score=input("what's score? ") lst=(name,int(score)) scores.append(lst) quits=input("would quit? (y or n) ") print(scores)
this different this because sorting strings and integers.
simply sort scores
key function sorts first item in tuple; 2nd item:
example:
from operator import itemgetter scores = sorted(scores, key=itemgetter(0, 1)) print(scores)
so final code sample this:
from operator import itemgetter scores=[] quits='' while quits!= 'y': name=input("what's name? ") score=input("what's score? ") lst=(name,int(score)) scores.append(lst) quits=input("would quit? (y or n) ") scores = sorted(scores, key=itemgetter(0, 1)) print(scores)
Comments
Post a Comment