I have a function that opens a file with the name: table1.txt and displays the values separated by commas in a specific format.
My function:
def sort_and_format(): contents = [] with open('table1.txt', 'r+') as f: for line in f: contents.append(line.split(',')) max_name_length = max([len(line[0]) for line in contents]) print(" Team Points Diff Goals \n") print("--------------------------------------------------------------------------\n") for i, line in enumerate(contents): line = [el.replace('\n', '') for el in line] print("{i:3} {0:{fill_width}} {1:3} {x:3} {2:3} :{3:3}".format(i=i+1, *line, x = (int(line[2])- int(line[3])), fill_width=max_name_length))
I figured out how to format it correctly for the table1.txt file:
FC Ingolstadt 04, 13, 4, 6 Hamburg, 9, 8, 10 SV Darmstadt 98, 9, 8, 9 Mainz, 9, 6, 9 FC Augsburg, 4, 7, 12 Werder Bremen, 6, 7, 12 Borussia Moenchengladbach, 6, 9, 15 Hoffenheim, 5, 8, 12 VfB Stuttgart, 4, 9, 17 Schalke 04, 16, 14, 3 Hannover 96, 2, 6, 18 Borrusia Dortmund, 16, 15, 4 Bayern Munich, 18, 18, 2 Bayer Leverkusen, 14, 11, 8 Eintracht Frankfurt, 9, 13, 9 Hertha BSC Berlin, 14, 5, 4 1. FC Cologne, 13, 10, 10 VfB Wolfsburg, 14, 10, 6
It outputs:
Team Points Diff Goals -------------------------------------------------------------------------- 1 FC Ingolstadt 04 13 -2 4 : 6 2 Hamburg 9 -2 8 : 10 3 SV Darmstadt 98 9 -1 8 : 9 4 Mainz 9 -3 6 : 9 5 FC Augsburg 4 -5 7 : 12 6 Werder Bremen 6 -5 7 : 12 7 Borussia Moenchengladbach 6 -6 9 : 15 8 Hoffenheim 5 -4 8 : 12 9 VfB Stuttgart 4 -8 9 : 17 10 Schalke 04 16 11 14 : 3 11 Hannover 96 2 -12 6 : 18 12 Borrusia Dortmund 16 11 15 : 4 13 Bayern Munich 18 16 18 : 2 14 Bayer Leverkusen 14 3 11 : 8 15 Eintracht Frankfurt 9 4 13 : 9 16 Hertha BSC Berlin 14 1 5 : 4 17 1. FC Cologne 13 0 10 : 10 18 VfB Wolfsburg 14 4 10 : 6
I’m trying to figure out how to sort a file so that the team with the highest points takes first place, and if the team has equal scores, then they are ranked by difference (difference in goals for and against the team), and if the difference is the same, they are ranked by goals scored.
I was thinking about implementing a bubble sort function similar to:
def bubble_sort(lst): j = len(lst) made_swap = True swaps = 0 while made_swap: made_swap = False for cnt in range (j-1): if lst[cnt] < lst[cnt+1]: lst[cnt], lst[cnt+1] = lst[cnt+1], lst[cnt] made_swap = True swaps = swaps + 1 return swaps
But I do not know how to isolate each row and compare the values with each other for sorting.