Нужны советы, чтобы сохранить код чистым, читаемым, организованным и, что самое важное, недостаточно контролируемым

Я начинающий программист на Python, и я начал свой самый первый проект, и я ищу совет, чтобы мой код был организован и не контролировался, потому что, поскольку мой код становится длиннее, кажется, что я понятия не имею, что происходит.

Краткий краткий обзор моего первого проекта:

Check the draw percentage of each group of football teams that are divided by a 
ranking order in EPL in recent 10  years.

  a. As EPL has 20 teams on the league, it has 4 groups in ascending order(1~5, 6~10
, 11~15, 16~20)

And I want to check if a specific group has a higher draw percentage than others.

Мой код Python:

1. Open csv files(the data which number of draw, number of all matches, their rank,
   and etc is already well orgranised in the table in excel
2. Read the data from csv files and put them into list in python
3. calculate the draw percentage
4. Write the calculated draw percentage in excel using xlsxwriter in python

Он работает очень хорошо, как я и предполагал, чтобы моя программа была, но проблема в том, что я не делаю свой код очень читабельным или разборчивым, если хотите. В основном у меня есть цикл 4 for, который выглядит примерно одинаково и избыточно, и мне интересно, есть ли способ сохранить мой код более организованным, например, как сделать цикл 4 для циклов в один цикл, чтобы вычислить весь процент отрисовки для 4 групп (Причины, по которым у меня есть 4 для цикла - это рассчитать процент ничьи для 4 групп).

Вот мой код, и любые советы по улучшению кода будут благодарны!

# To create an excel file, we must import xlsxwriter
import xlsxwriter
import csv

# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook("Draw percentage of 4 groups in EPL in recent"
                                " 10 years.xlsx")

# The workbook object is used to add a new worksheet via the add_worksheet
# method
worksheet = workbook.add_worksheet()

# And then, let's write some header bro
worksheet.write(0, 0, "SEASON")
worksheet.write(0, 1, "A")
worksheet.write(0, 2, "B")
worksheet.write(0, 3, "C")
worksheet.write(0, 4, "D")

# The reason i put this as 2006, 2007 is I wanted to avoid put another useless
# variable to exectue the for loop. So, as for loop starts, it will add 1 to
# the variable year1 and year2, so it will start from epl20072008.csv file
year1 = 2006
year2 = 2007

# For the excel worksheet repeating
# variable 'row' starts with 1 because we already wrote the header
excel_row = 1

# repeat for 11 times
for i in range(0, 11):
    year1 += 1
    year2 += 1

    # for excelsheet, so everytime for loop runs, it is set to 0
    excel_col = 0

    file = 'epl' + str(year1) + str(year2) + ".csv"

    #read the csv file
    with open(file) as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')

        # make the list
        ranks = []
        team_names = []
        total_matches = []
        num_draws = []


        # put the values into the list('rank', 'team_names', etc) that we
        # made above
        count = 0
        for row in readCSV:
            # We will skip the first row, which has names of the variable in
            # Excel
            if count==0:
                count += 1
                continue

            rank = row[0]
            team_name = row[1]
            total_match = row[2]
            num_draw = row[4]

            ranks.append(rank)
            team_names.append(team_name)
            total_matches.append(total_match)
            num_draws.append(num_draw)

        # START OF THE NEW SEASON
        print("---------------------------------------")
        print("EPL" + str(year1) + str(year2) + " SEASON")
        print("---------------------------------------")

        worksheet.write(excel_row, excel_col, file)


        # print each team's draw ratio
        num_of_teams = 20
        for i in range(0, num_of_teams):
            print("Rank:", ranks[i], ", Team:", team_names[i], ", Total match:",
                  total_matches[i], ", number of draws:", num_draws[i])

            # Because it is string format, convert it to float to calculate
            total_match = float(total_matches[i])
            num_draw = float(num_draws[i])
            draw_ratio = num_draw/total_match

            print("Draw ratio of", team_names[i], ":", str(draw_ratio*100)+"%")
            print()

        # Make 4 groups to present the draw percentage
        one_to_five = {}
        six_to_ten = {}
        eleven_to_fifteen = {}
        sixteen_to_twenty = {}

        # Let's make for loop for each group
        # This one looks very very unefficient!!!!!!!!!!!
        # CAN WE FIND A BETTER WAY?
        # Possibly we can find a way to make these 3 for loops to one for loop?
        teams = []
        total_match = []
        number_draw = []
        num_match = 0
        num_draw = 0
        for i in range(0, 5):
            teams.append(team_names[i])
            total_match.append(total_matches[i])
            number_draw.append(num_draws[i])
            num_match += float(total_matches[i])
            num_draw += float(num_draws[i])

        # THIS IS THE DRAW RATIO OF EACH GROUP THAT WE ARE LOOKING FOR
        draw_percent = num_draw/num_match
        worksheet.write(excel_row, excel_col + 1, draw_percent)

        one_to_five["team"] = teams
        one_to_five["matches"] = total_match
        one_to_five["number of draws"] = number_draw
        one_to_five["draw percentage"] = draw_percent

        print("Group1: ")
        print(one_to_five)
        print("--------------------------------------")

        teams = []
        total_match = []
        number_draw = []
        num_match = 0
        num_draw = 0
        for i in range(5, 10):
            teams.append(team_names[i])
            total_match.append(total_matches[i])
            number_draw.append(num_draws[i])
            num_match += float(total_matches[i])
            num_draw += float(num_draws[i])

        draw_percent = num_draw/num_match
        worksheet.write(excel_row, excel_col + 2, draw_percent)

        six_to_ten["team"] = teams
        six_to_ten["matches"] = total_match
        six_to_ten["number of draws"] = number_draw
        six_to_ten["draw percentage"] = draw_percent

        print("Group2: ")
        print(six_to_ten)
        print("--------------------------------------")

        teams = []
        total_match = []
        number_draw = []
        num_match = 0
        num_draw = 0
        for i in range(10, 15):
            teams.append(team_names[i])
            total_match.append(total_matches[i])
            number_draw.append(num_draws[i])
            num_match += float(total_matches[i])
            num_draw += float(num_draws[i])

        draw_percent = num_draw/num_match
        worksheet.write(excel_row, excel_col + 3, draw_percent)

        eleven_to_fifteen["team"] = teams
        eleven_to_fifteen["matches"] = total_match
        eleven_to_fifteen["number of draws"] = number_draw
        eleven_to_fifteen["draw percentage"] = draw_percent
        print("Group3: ")
        print(eleven_to_fifteen)
        print("--------------------------------------")

        teams = []
        total_match = []
        number_draw = []
        num_match = 0
        num_draw = 0
        for i in range(15, 20):
            teams.append(team_names[i])
            # save them as float, because later we have to calculate the draw
            # percentage
            total_match.append(float(total_matches[i]))
            number_draw.append(float(num_draws[i]))
            num_match += float(total_matches[i])
            num_draw += float(num_draws[i])
        draw_percent = num_draw/num_match
        worksheet.write(excel_row, excel_col + 4, draw_percent)

        sixteen_to_twenty["team"] = teams
        sixteen_to_twenty["matches"] = total_match
        sixteen_to_twenty["number of draws"] = number_draw
        sixteen_to_twenty["draw percentage"] = draw_percent
        print("Group4: ")
        print(sixteen_to_twenty)
        print("--------------------------------------")

        # Change the row in excel sheet
        excel_row += 1

0 ответов

Другие вопросы по тегам