Python入门:Error handling

2016-05-17  本文已影响43人  不务正业的Yuez
## 2. Sets ##

import csv

legislators = list(csv.reader(open("legislators.csv", "r")))

gender = []
for ll in legislators:
    gender.append(ll[3])
    
gender = set(gender)
print(gender)

## 3. Exploring the dataset ##

party = []
for ll in legislators:
    party.append(ll[-1])
party = set(party)
print(party)
print(legislators)

## 4. Missing values ##

for row in legislators:
    if row[3] == "":
        row[3] = "M"

## 5. Parsing birth years ##

birth_years = []

for row in legislators:
    parts = row[2].split("-")
    birth_years.append(parts[0])

## 6. Try/except blocks ##

try:
    float(hello)
except Exception:
    print("Error converting to float.")

## 7. Exception instances ##

try:
    int("")
except Exception as exc:
    print(type(exc))
    print(str(exc))

## 8. The pass keyword ##

converted_years = []

for element in birth_years:
    year = element
    try:
        year = int(year)
    except Exception:
        pass
    converted_years.append(year)

## 9. Convert birth years to integers ##

for row in legislators:
    year = row[2].split("-")[0]
    try:
        birth_year = int(year)
    except Exception:
        birth_year = 0
    row.append(birth_year)

## 10. Fill in years without a value ##

last_value = 1
for row in legislators:
    if row[7] == 0:
        row[7] = last_value
    last_value = row[7]
上一篇下一篇

猜你喜欢

热点阅读