Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # A text file contains the following lines:
- # last name, first name, middle name, birth year
- # Output required:
- # first initial, 2nd initial, last name, birth year
- # The output is to be in ascending order of birth year
- # Where 2 students have the same birth year, list then in the order they appeared in input file
- # Here is my input as it might appear in a list of lines read in from an input file
- # Note that the 2nd and 4th students have the same birth year, and must appear in the output with Jones before Fox
- my_input = ["John,William,Smith,1990", "Lucy,Mary,Jones,1992", "Jack,Amos,Black,1991", "Brenda,Kate,Fox,1992"]
- my_temp = [] # Define an empty list into which we will put the data to be sorted
- for x, line_in in enumerate(my_input): # 'enumerate' gives us the index of a line in the input, plus the line
- data_list = line_in.split(',') # split the input line on comma, giving a list of data items
- year = data_list[3] # year is item 3 from input line
- surname = data_list[2] # surname is item 2
- first_initial = data_list[0][0] # get the initial only from first name
- middle_initial = data_list[1][0] # get the initial only from middle name
- # Add a tuple to our temp list, ready for sorting
- # Note that we include 'x' which is the index from the input list,
- # so that we get the desired sequence where equal birth years exist
- my_temp.append((year, x, first_initial, middle_initial, surname))
- # Sort the temp list in situ
- my_temp.sort()
- # Iterate through the sorted list, printing the required items
- for data in my_temp:
- print(f"{data[0]} {data[2]} {data[3]} {data[4]}")
- # Output:
- # 1990 J W Smith
- # 1991 J A Black
- # 1992 L M Jones
- # 1992 B K Fox
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement