python自学大数据 爬虫Python AI Sql

challenge :modules,error handlin

2018-03-15  本文已影响9人  钊钖

In this challenge, you'll practice using modules, classes, and list comprehensions to process and represent a data set in Python. You'll be working with data on NFL player suspensions.


import csv

nfl_suspensions = list (csv.reader(open('nfl_suspensions_data.csv','r')))
nfl_suspensions = nfl_suspensions[1:]

years ={}
for row in nfl_suspensions:
    year = row[5]
    if year in years:
        years[year]+=1
    else:
        years[year] =1
print(years)

Let's explore the values in these columns by using sets and list comprehensions.


teams = [row[1] for row in nfl_suspensions]
unique_teams = set(teams)

unique_games = set([row[2] for row in nfl_suspensions])

print (unique_teams)
print (unique_games)

class Suspension:
    def __init__(self,row):
        self.name = row[0]
        self.team = row[1]
        self.games= row[2]
        self.year = row[3]
        
third_suspension = Suspension(nfl_suspensions[2])

print(third_suspension)
print(third_suspension.team)
print(third_suspension.name)


Let's tweak the Suspension class a bit to extend its functionality. Right now, the value for year is a string, rather than an integer. Let's modify the Suspension class so that it stores the values as integers.


class Suspension:
    def __init__(self,row):
        self.name = row[0]
        self.team = row[1]
        self.games= row[2]
        try :
            self.year =int(row[5])
        except Exception:
            self.year = 0
    def get_year(self):
        return self.year
    
missing_year = Suspension(nfl_suspensions[22])
twenty_third_year = missing_year.get_year()
twenty_third_year

上一篇 下一篇

猜你喜欢

热点阅读