Jump to content

need help sorting a list of tuples in python 3

Go to solution Solved by Nuluvius,

I'll let you sort your print formatting out. Basically you were sorting strings and not Integers.

in_file = open("scores.txt")high_scores = []for line in in_file:    score, name = line.split(", ")    high_scores += [(int(score), name)]print(high_scores)high_scores = sorted(high_scores, key=lambda tup: tup[0])print(high_scores)
[(3, 'Nuno Bettencourt\n'), (4, 'Jimi Hendrix\n'), (5, 'Lincoln Brewster'), (12, 'Eric Gales\n')]

I need help sorting my list of tuples it needs to be from least to greatest.

Any help would be greatly apreciated :)

in_file = open("scores.txt")high_scores = []for line in in_file:    score, name = line.split(", ")    high_scores += [(score, name)]print(high_scores)high_scores = sorted(high_scores)  ##NOT WORKINGprint(high_scores)for scores in high_scores:    score, name = scores[0], scores[1].strip()        space_to_add_to_name = 28 - len(name)    name += " " * space_to_add_to_name         space_to_add_to_score = 3 - len(score)    score = " " * space_to_add_to_score + score    print(name + score)

the scores.txt

4, Jimi Hendrix3, Nuno Bettencourt12, Eric Gales5, Lincoln Brewster

console output

[('4', 'Jimi Hendrix'), ('3', 'Nuno Bettencourt'), ('12', 'Eric Gales'), ('5', 'Lincoln Brewster')][('12', 'Eric Gales'), ('3', 'Nuno Bettencourt'), ('4', 'Jimi Hendrix'), ('5', 'Lincoln Brewster')]Eric Gales                   12Nuno Bettencourt              3Jimi Hendrix                  4Lincoln Brewster              5
Link to post
Share on other sites

I'll let you sort your print formatting out. Basically you were sorting strings and not Integers.

in_file = open("scores.txt")high_scores = []for line in in_file:    score, name = line.split(", ")    high_scores += [(int(score), name)]print(high_scores)high_scores = sorted(high_scores, key=lambda tup: tup[0])print(high_scores)
[(3, 'Nuno Bettencourt\n'), (4, 'Jimi Hendrix\n'), (5, 'Lincoln Brewster'), (12, 'Eric Gales\n')]

The single biggest problem in communication is the illusion that it has taken place.

Link to post
Share on other sites

 

I'll let you sort your print formatting out. Basically you were sorting strings and not Integers.

in_file = open("scores.txt")high_scores = []for line in in_file:    score, name = line.split(", ")    high_scores += [(int(score), name)]print(high_scores)high_scores = sorted(high_scores, key=lambda tup: tup[0])print(high_scores)
[(3, 'Nuno Bettencourt\n'), (4, 'Jimi Hendrix\n'), (5, 'Lincoln Brewster'), (12, 'Eric Gales\n')]

thank you so much don't know how i missed that one :P

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×