我一直在阅读DataQuest“Python简介”程序,在本课程的“模块”部分中,有一节关于定义函数。我完成了那个部分但后来决定我想尝试扩展它。有效的原始代码是:
#!/usr/bin/env python3
import csv
f = open("nfl.csv", 'r')
nfl = list(csv.reader(f))
# Define your function here.
def nfl_wins(team):
count = 0
for row in nfl:
if row[2] == team:
count += 1
return count
cowboys_wins = nfl_wins("Dallas Cowboys")
falcons_wins = nfl_wins("Atlanta Falcons")
print(cowboys_wins)
print(falcons_wins)
我的代码旨在迭代一个包含所有团队的列表并给出每个团队的胜利数量,如下所示:
#!/usr/bin/env python3
import csv
f = open('nfl.csv', 'r')
nfl = list(csv.reader(f))
# Define your function here.
def nfl_wins(team):
print(team)
count = 0
for row in nfl:
if row[2] == team:
count = count + 1
return count
nfl_teams = ['Denver Broncos', 'Detroit Lions', 'Green Bay Packers', 'Houston Texans', 'Indianapolis Colts', 'Jacksonville Jaguars', 'Kansas City Chiefs', 'Miami Dolphins', 'Minnesota Vikings', 'New England Patriots', 'New Orleans Saints', 'New York Giants', 'New York Jets', 'Oakland Raiders', 'Philadelphia Eagles', 'Pittsburgh Steelers', 'San Diego Chargers', 'San Francisco 49ers', 'Seattle Seahawks', 'St. Louis Rams', 'Tampa Bay Buccaneers', 'Tennessee Titans', 'Washington Redskins']
for squad in nfl_teams:
print(squad, nfl_wins(squad))
当我只是遍历“nfl_teams”列表并打印名称时,它工作正常。当我尝试将团队名称传递给“nfl_wins”函数时,我收到以下错误:
$ python3 nfl_wins.py
Denver Broncos
Traceback (most recent call last):
File "nfl_wins.py", line 20, in <module>
print(squad, nfl_wins(squad))
File "nfl_wins.py", line 13, in nfl_wins
if row[2] == team:
IndexError: list index out of range
我的环境是在Windows 7企业版下运行的Cygwin上的Python 3.4.3。