Advertisement
acclivity

pyStudentListCreation

Jan 12th, 2023
798
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | Software | 0 0
  1. # A text file contains the following lines:
  2. # last name, first name, middle name, birth year
  3. # Output required:
  4. # first initial, 2nd initial, last name, birth year
  5. # The output is to be in ascending order of birth year
  6. # Where 2 students have the same birth year, list then in the order they appeared in input file
  7.  
  8.  
  9. # Here is my input as it might appear in a list of lines read in from an input file
  10. # Note that the 2nd and 4th students have the same birth year, and must appear in the output with Jones before Fox
  11. my_input = ["John,William,Smith,1990", "Lucy,Mary,Jones,1992", "Jack,Amos,Black,1991", "Brenda,Kate,Fox,1992"]
  12.  
  13. my_temp = []            # Define an empty list into which we will put the data to be sorted
  14.  
  15. for x, line_in in enumerate(my_input):      # 'enumerate' gives us the index of a line in the input, plus the line
  16.  
  17.     data_list = line_in.split(',')          # split the input line on comma, giving a list of data items
  18.  
  19.     year = data_list[3]                     # year is item 3 from input line
  20.     surname = data_list[2]                  # surname is item 2
  21.     first_initial = data_list[0][0]         # get the initial only from first name
  22.     middle_initial = data_list[1][0]        # get the initial only from middle name
  23.  
  24.     # Add a tuple to our temp list, ready for sorting
  25.     # Note that we include 'x' which is the index from the input list,
  26.     # so that we get the desired sequence where equal birth years exist
  27.     my_temp.append((year, x, first_initial, middle_initial, surname))
  28.  
  29. # Sort the temp list in situ
  30. my_temp.sort()
  31.  
  32. # Iterate through the sorted list, printing the required items
  33. for data in my_temp:
  34.     print(f"{data[0]} {data[2]} {data[3]} {data[4]}")
  35.  
  36. # Output:
  37. # 1990 J W Smith
  38. # 1991 J A Black
  39. # 1992 L M Jones
  40. # 1992 B K Fox
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement