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
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
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)