-2

I've been having trouble combining to different lists I'm trying to get a list of names and a list of scores, while taking the top n students scores with the names showing.

I'm also unsure where to put the return function in it

pigletfly
  • 1,051
  • 1
  • 16
  • 32
Darian Lee
  • 19
  • 1
  • 1
  • 2
  • 2
    This question is not answerable in its current form. At the very least, please provide example input and expected output. If you have, please also show what you have tried so far. – 5gon12eder Jun 23 '15 at 01:39
  • Please add more information! – Juan David Jun 23 '15 at 01:47
  • From the rather vague description, it sounds like you'd want a dict (with the scores as keys, and names as values), then sort on the scores (or dict keys) to get the names of the top students. –  Jun 23 '15 at 01:55

1 Answers1

2

I'm going to assume you have some data that looks like:

names = ['Alice', 'Bob', "Charlie", "David", "Eve"]
scores = [1, 2, 3, 4, 5]

and you're trying to get the top n (for ease of use, we'll use n=2) names, as sorted by score. There's lots of ways to do this, the easiest way is to use a dictionary. We want to end up with:

name_score_dict = {"Alice": 1,
                   "Bob": 2,
                   "Charlie": 3,
                   "David": 4,
                   "Eve": 5}

And we can do that in a few different ways, but zip is crucial no matter how. The easiest to understand is probably using a dict comprehension.

name_score_dict = {name:score for name,score in zip(names, scores)}

More compact, but possibly harder to understand, is using the dict constructor

name_score_dict = dict(zip(names, scores))

Now all you have to do is to get the dictionary in some sort of a sorted state. There's a bajillion different questions on Stack Overflow on how to sort a dictionary, which I will leave you to read to understand why what I'm doing makes sense, but:

sorted_d = sorted(name_score_dict.items(), key=lambda kv: kv[1], reverse=True)

This should give you something like:

[("Eve", 5), ("David", 4), ("Charlie", 3), ("Bob", 2), ("Alice", 1)]

So slice off the first n items to get name, score tuples.

for name,score in sorted_d[:n]:
    print("Name is {} and score is {}".format(name, score))

(this also uses string formatting, which is worth learning on its own)

Community
  • 1
  • 1
Adam Smith
  • 52,157
  • 12
  • 73
  • 112