我相对较新的Python并且在文件中输入和输出。这是输入文件:
1 3
1 1
1 0
20 30
这是我的代码,将其作为“soccer_in.txt”,并假设将以下内容输出到“soccer_out.txt”:
Season: 1, Games Played: 1, Points earned: 3
Possible Win-Tie-Loss Records
-----------------------------
1-0-0
Season: 2, Games Played: 1, Points earned: 1
Possible Win-Tie-Loss Records
-----------------------------
0-1-0
Season: 3, Games Played: 1, Points earned: 0
Possible Win-Tie-Loss Records
-----------------------------
0-0-1
Season: 4, Games Played: 20, Points earned: 30
Possible Win-Tie-Loss Records
-----------------------------
10-0-10
9-3-8
8-6-6
7-9-4
6-12-2
5-15-0
使用此代码:
def process_season(output_file, season, games_played, points_earned):
output_file.write("Season: " + str(season) + ", Games Played: " + str(games_played) +
", Points earned: " + str(points_earned))
output_file.write("Possible Win-Tie-Loss Records")
output_file.write("-----------------------------")
wins = points_earned // 3
ties = points_earned % 3
losses = games_played - wins - ties
while (wins >= 0) and (losses >= 0):
output_file.write(str(wins) + "-" + str(ties) + "-" + str(losses))
wins -= 1
ties += 3
losses -= 2
output_file.write()
# --------------------------------------
def process_seasons(input_file, output_file):
season_number = 0
for season in input_file:
season_number += 1
process_season(output_file, season_number, season[0], season[1])
# --------------------------------------
f_in=open("soccer-in.txt", "r")
f_out=open("soccer-out.txt", "w+")
process_seasons(f_in, f_out)
但是我收到了一个错误 在process_season中的文件“C:\ Users”,第12行 wins = points_earned // 3 TypeError://:'str'和'int'
的不支持的操作数类型任何帮助将不胜感激谢谢。
答案 0 :(得分:1)
您正在尝试分割字符串。
在process_season()
中,您可以尝试将season[0]
和season[1]
视为整数。
process_season(output_file, season_number, int(season[0]), int(season[1]))