## 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搜索了很久,看了一些不靠譜的解決方案浪...