问题
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