每当我运行此代码时,它都会"告诉"我出现了一个错误,我需要做些什么才能让它告诉我团队出现在列表中的次数。给出的列表是WorldSeriesWinners。wins=0
try:
input_file = open('WorldSeriesWinners.txt')
team = input('Enter the team name: ')
winner = input_file.readlines()
for i in range(len(winner)):
winner[i] = float(winner[i])
if team in winner[i]:
wins += 1
print('The team ', team, ' won ', wins, ' World Series')
except IOError:
print('The file could not be found.')
except IndexError:
print('There was an indexing error.')
except:
print('An error occurred.')
这里并没有真正回答您的问题,但我忍不住提出了一种更像蟒蛇的实现方式:
with open('WorldSeriesWinners.txt', 'r') as f:
winners = [team.rstrip() for team in f.readlines()]
team = input('Enter the team name: ')
print(f'{team} won {winners.count(team)} world series')
一些快速解释:
f.readlines()
是所有行的列表(存储为字符串(。但是,其中包括换行符"\n"。方法.rstrip()
去除字符串开头或结尾的空白,包括新行。[team.rstrip() for team in f.readlines()]
就是我们所说的列表理解。count()
方法计算潜在元素的出现次数;winners.count('New York Yankees')
返回洋基队出现在名单中的次数。字符串
f'{team} won {winners.count(team)} world series'
就是我们所说的f-string(在Python 3.6及以上版本中实现(。它是'{} won {} world series'.format(team, winners.count(team)
的一个非常方便的等价物,所以请记住它。
所以。。。您不应该将获胜者的名字转换为float
。此外,在用户传入单个字符的情况下,不应该使用in
。这是更新后的代码:
wins = 0
input_file = open('WorldSeriesWinners.txt', 'r') # Specify to read file
team = input('Enter the team name: ')
winner = input_file.read().split("n") # Removes "n" on each line
for i in range(len(winner)):
if winner[i] == team: # Check if inpout is equal instead of inside string
wins += 1
print('The team', team, 'won', wins, 'World Series')
执行for winner in winners
而不是for i in range(len(winner)):