我是 django 的新手,想通过简单的 django 应用程序来了解更多信息,在代码中的一个地方我不得不选择 locationName
并获取与 locationName
匹配相同 ID 的元素在一张 table 上。当我开始想是continue
逃避 for 循环的最 pythonic 方式?
有问题的代码如下:
for locationName in locationGroup:
idRef = locationName.id
try:
element = location.objects.order_by('-id').filter(name__id=idRef)[0]
except IndexError:
continue
最佳答案
如果在 except 子句之后有一些您不想执行的代码,continue
是完全有效的,否则有些人可能会觉得 pass
更合适。
for x in range(y):
try:
do_something()
except SomeException:
continue
# The following line will not get executed for the current x value if a SomeException is raised
do_another_thing()
for x in range(y):
try:
do_something()
except SomeException:
pass
# The following line will get executed regardless of whether SomeException is thrown or not
do_another_thing()
关于python - "continue"是逃离 try catch block 的 Pythonic 方式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11467985/