这是我的任务:
我目前在第2a部分(打印所有玩了1700分钟以上的玩家)
这是我目前的代码:
def part1():
createfile=open("Assignment4.txt", "a+")
createfile.write(f"Player Name MinsPlayed Goals Assists YellowCard\n")
createfile.write(f"Lionel Messi 1943 19 4 4\n")
createfile.write(f"Robert Lewandowski 1864 28 6 2\n")
createfile.write(f"Harry Kane 2017 14 11 1\n")
createfile.write(f"Jack Grealish 1977 6 10 6\n")
createfile.write(f"Cristiano Ronaldo 1722 19 3 1\n")
createfile.write(f"Zlatan Ibrahimovic 1102 14 1 2\n")
createfile.write(f"Gerard Moreno 1735 14 2 3\n")
createfile.write(f"Romelu Lukaku 1774 18 6 4\n")
createfile.write(f"Kylian Mbappe 1706 18 6 3\n")
createfile.write(f"Erlin Haaland 1542 17 4 2")
createfile.close()
part1()
def part2():
filetoopen=open("Assignment4.txt", "r")
for line in filetoopen.readlines():
linetosplit=line.split(' ')
players = []
player_name = (linetosplit[0] + ' ' + linetosplit[1])
mins_played = (linetosplit[2])
goals = (linetosplit[3])
assists = (linetosplit[4])
yellow_card = (linetosplit[5])
players.append([player_name, mins_played, goals, assists, yellow_card])
filetoopen.close()
if mins_played > 1700:
print(player_name)
part2()
当我运行它时,会弹出此错误消息
TypeError: '>' not supported between instances of 'str' and 'int'
然后我试着通过改变来修复它
mins_played = (linetosplit[2])
到
mins_played = int(linetosplit[2])
但随后出现了这个错误消息
ValueError: invalid literal for int() with base 10: ''
检查
linetosplit
实际返回的内容。在本例中,您将看到它返回因为所有的空间都被分割了。正如@Reti43所提到的,
line.split(' ')
和line.split()
之间存在差异然而,在你的情况下,这并不能完全解决你的问题。因为文件的第一行是每个列的定义。并且不能将此字符串转换为整数
一种解决方法是在循环时不包括第一行。有多种不同的方法可以做到这一点,但是我通过排除列表中的第一项来使用列表操作
这不包括第一行
相关问题 更多 >
编程相关推荐