4

我是 django 的新手,想通过简单的 django 应用程序来了解更多信息,在代码中的一个地方,我必须选择locationName并获取与表中相同locationName的 id 匹配的元素。当我开始想知道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
4

4 回答 4

9

如果有一些你不想在 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() 
于 2012-07-13T10:27:59.683 回答
3

这正是continue/break关键字的用途,所以是的,这是最简单和最 Pythonic 的方式。

应该有一种——最好只有一种——明显的方法来做到这一点。

于 2012-07-13T10:05:39.187 回答
2

你应该使用

try:
    element = location.objects.order_by('-id').filter(name__id=idRef)[0]
except IndexError:
    pass
于 2012-07-13T09:45:37.187 回答
1

你很难说出你在做什么。该代码通过查看第一个元素并捕获 IndexError 来检查您是否从查询中获得任何行。

我会以一种使这个意图更加清晰的方式来编写它:

for locationName in locationGroup:
    idRef = locationName.id
    rows = location.objects.order_by('-id').filter(name__id=idRef)
    if rows: # if we have rows do stuff otherwise continue
         element = rows[0]
         ...

在这种情况下,您可以使用getwhich 使其更加清晰:

for locationName in locationGroup:
    idRef = locationName.id
    try:
         element = location.objects.get(name__id=idRef)
    except location.DoesNotExist:
         pass
于 2012-07-13T10:41:22.310 回答