## 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]
Python入门:Error handling
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 首先喷一句:windows下搞开发真的环境很蛋疼.... 出现标题的这个错误,怎么解决呢? 直接去这里下载mysq...
- If you're using Windows you can now install all node-gypd...
- 在使用pip命令安装selenium和appium-python-client时,总报错:Unicode Deco...
- 原文发表自 szhshp的第三边境研究所 , 转载请注明 gyp ERR! stack Error: C...
- 在linux系统安装MySQL-Python模块一直在报这个错,Google搜索了很久,看了一些不靠谱的解决方案浪...