Search code examples
pythonleaderboard

Python creating 2 lists of name and score for high scores


I'm trying to append more items to this 2 list after getting the input and score from my game, I need to know how am I able to print both names and score side by side as the code below is what I learnt from geeksforgeeks.org. I'm not really sure if this code is meant for this.

Am I in the right direction as I'm new to this and I need guidance, please advice thanks!

name=["Mary","Lisa","Lumby"]
score=[5,7,4]

def sort_list(list1, list2):
 
    zipped_pairs = zip(list2, list1)
 
    z = [x for _, x in sorted(zipped_pairs)]
 
    return z

print(sort_list(name, score))

The result I currently get is this but I only needed the names without brackets. and I was hoping I can append more results into the list and print the top 3 scores starting with lowest scores. ['Lumby', 'Mary', 'Lisa']


Solution

  • Rather than parallel lists you should use a dictionary. Something like this:

    data = {'Mary': 5, 'Lisa': 7, 'Lumby': 4}
    
    for t in sorted(data.items(), key=lambda e: e[1])[-3:]:
        print(*t)
    

    This will print the top 3 names and scores from the dictionary in ascending order as follows:

    Lumby 4
    Mary 5
    Lisa 7
    

    Now let's do this:

    data['Jo'] = 10
    

    Run the code again then:

    Mary 5
    Lisa 7
    Jo 10
    

    If you insist on using a pair of lists then:

    name = ["Mary", "Lisa", "Lumby"]
    score = [5, 7, 4]
    
    for s, n in sorted(zip(score, name))[-3:]:
        print(n, s)