在列表理解中将str转换为int

时间:2018-08-08 11:20:06

标签: python python-3.x list-comprehension

我有一个以年份为字符串的列表,但是缺少的年份很少用空字符串表示。

我正在尝试将那些字符串转换为整数,并跳过使用列表推导和try andexcept子句无法转换的值?

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

我尝试了此代码,但无法正常工作。

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

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

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

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