你当然可以一起破解一些东西,但它不是特别可读。
(_ for _ in ())
定义了一个生成器,您可以从中使用该throw
方法来引发您想要的任何异常。
all((_ for _ in ()).throw(somecustomException(value)) for value in required_values if value not in some_map)
也就是说,抛开可读性不谈,除非你真的要使用列表,否则使用列表推导是没有意义的。这可能更有意义,例如:
map_values=[some_map[value] if value in some_map else (_ for _ in ()).throw(somecustomException(value)) for value in required_values]
But even then it probably makes more sense to handle the exception outside the loop. If you want to raise a custom exception for some reason you can just catch the KeyError and raise your own exception.
try:
found_values=[some_map[value] for value in required_values]
except KeyError as e:
raise somecustomException(e.args[0])