converting str to int in list comprehension
本问题已经有最佳答案,请猛点这里访问。
我有一个用年份作为字符串的列表,但是有一些缺失的年份用空字符串表示。
我正在尝试将这些字符串转换为整数,并跳过使用列表理解和try and except子句无法转换的值?
1 | birth_years = ['1993','1994', '' ,'1996', '1997', '', '2000', '2002'] |
我试过这个代码,但没用。
1 2 3 4 5 6 7 | try: converted_years = [int(year) for year in birth_years] except ValueError: pass required output: converted_years = ['1993','1994','1996', '1997', '2000', '2002'] |
1 | converted_years = [int(year) for year in birth_years if year] |
1 | converted_years = [int(x) for x in birth_years if x.isdigit()] |