list_of_strings = ["a", "2", "7", "zebra"]
def safe_int(list):
try:
list[i] = int(list[i])
except ValueError:
list[i] = 0
new_list = [safe_int(list_of_strings) for i in range(len(list_of_strings))]
print new_list
答案 0 :(得分:1)
定义你的函数,使它返回转换结果或数字零
def safe_int(l, i):
try:
return int(l[i])
except ValueError:
return 0
(请注意,我已经明确地将i
传递给函数,因为在函数中可以看到列表推导中i
的值,因为Python 2中的错误设计决策已在Python 3)然后构建new_list
new_list = [ safe_int(list_of_strings, i) for ...]
我必须说你的方法不是惯用的,我更愿意写
def safe_int(a_string):
try:
return int(a_string)
except ValueError:
return 0
new_list = [safe_int(s) for s in list_of_strings]