converting str to int in list comprehension [duplicate]

僤鯓⒐⒋嵵緔 提交于 2021-02-05 10:54:48

问题


I have a list with years as strings but there are few missing years which are represented as empty strings.

I am trying to convert those strings to integers and skip the values which can't be converted using list comprehension and try and except clause?

birth_years = ['1993','1994', '' ,'1996', '1997', '', '2000', '2002']

I tried this code but it's not working.

try:
    converted_years = [int(year) for year  in birth_years]
except ValueError:
    pass

required output:
converted_years = ['1993','1994','1996', '1997', '2000', '2002']

回答1:


[int(year) for year in birth_years if year.isdigit()]




回答2:


converted_years = [int(year) for year in birth_years if year]



回答3:


converted_years = [int(x) for x in birth_years if x.isdigit()]


来源:https://stackoverflow.com/questions/51745416/converting-str-to-int-in-list-comprehension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!