你不能. try
is a (复合)陈述 https://docs.python.org/3.5/reference/compound_stmts.html,列表理解是表达 https://docs.python.org/3.5/reference/expressions.html。在 Python 中,这些是完全不同的东西,而你cannot表达式中有一个语句。
您可以做的就是使用包装函数:
def add_handler(handler, exc, func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except exc:
return handler(*args, **kwargs) # ???
return wrapper
然后用作:
my_truediv = add_handler(print, ZeroDivisionError, truediv)
请注意,这是非常有限。您必须返回一个值并将其插入结果列表中,不能简单地“跳过它”。
你应该简单地做:
from operator import truediv
result_list = []
for i, j in zip(list1, list2):
try:
result_list.append(i/j)
except ZeroDivisionError:
pass
或者,如果您只是想跳过这些值,您可以将它们过滤掉:
map(lambda x_y: truediv(*x_y), filter(lambda x_y: x_y[1] != 0, zip(list1, list2)))