jeudi 22 juillet 2021

How can I print strings based on ascending order of an index within a tuple

I have 3 groups of student results: group_a, group_b and group_c

Each group contains a list of tuples which take this order: (student_number,score).

I would like to print a message for each student depending on their score:

  • Each student within Group A : "Well done student {}. Your score was {}"
  • Each student within Group B : "Good work student {}. Your score was {}"
  • Each student within Group C : "Hi student {}. Your score was {}. You can do better than this."

In an attempt to achieve this, I combined all 3 groups before sorting them by the first element of the tuple.

  all_groups = group_a + group_b + group_c
  
  # take first element for sort

  def takeFirst(elem):
    return elem[0] 

 #using the 'takeFirst' function, sort tuple based on the first element
  all_groups.sort(key=takeFirst)

#each tuple reflects (student number, score)
  print(all_groups)
 [(1, 29), (2, 54), (3, 52), (4, 50), (5, 30), (6, 57), (7, 56), (8, 47), (9, 51), (10, 55)]

Next, I printed a message for each student depending on their score.

collection4 = []
collection5 = []
collection6 = []

for number, pair1 in enumerate(all_groups):
    # Unpack pair1: number, student_score
    student_number, score1 = pair1
    # print msg for each student. Attach every sentence into a 'collection' bucket.
    if score1 >=60:
        collection4.append('Well done student {}. Your score was {}.'.format(student_number, score1))
    elif score1 >=50 and score1<=59:
        collection5.append('Good work student {}. Your score was {}.'.format(student_number, score1))
    else:
        collection6.append('Hi student {}. Your score was {}. You can do better than this.'.format(student_number, score1))

Next, I combined collection 4, 5 and 6 into one bucket.

totalcollection = collection4 + collection5 + collection6

However, when I print the content of the 'totalcollection' variable, the results are not ordered in ascending order of the student number.

May I know how I can solve this problem? Thank you.

Aucun commentaire:

Enregistrer un commentaire