使用python不中断仅更新队列中第一次出现的对象

时间:2018-02-13 22:09:54

标签: python loops queue

我在python中创建了一个函数,它将改变第一次出现一个对象的优先级,但是我无法修复它,因此它只能在第一次出现时使用而不使用break。在我下面的代码中,我使用了break,它按预期工作,但我不想使用它。

    def update_priority(self, object, priority):

for i in range(len(self._queue)):
    if object == self._queue[i].get_item():
        # checking object already has that priority
        if priority == self._queue[i].get_priority():
            # dont change if it has the priority
            pass
        # if the object does not have that priority set to new
        else:
            self._queue[i].set_priority(pri)
            break
    else:
        pass

2 个答案:

答案 0 :(得分:1)

听起来您还想学习如何减少代码的长度。根据经验,首先要集中精力使代码清晰简洁,这样您就可以尝试找出简化结构的方法。例如,您可以重组和删除冗余分支。你的许多案件都是通行证。同样,是的,大学课程说断言并不是很好。为清楚起见,您可能希望使用条件变量来结束循环。在这种情况下,你真的不需要这样做,但另一种方法是将代码包装在一个函数中并简单地通过return绕过循环的其余部分,你已经使用了一个函数,所以如果你所做的只是更新一个项目的优先级(并退出),你可以从函数返回。也许您想要返回一个状态代码,指示是否找到了某个项目。 (TrueFalse)。

def update_priority(self, object, priority):
    # check all items in the queue (you do not require the index.)
    # the entry is stored in "entry"
    for entry in self._queue:
        # if you find the object and its priority needs an update
        if object == entry.get_item() and priority != entry.get_priority():
            # set the priority
            entry.set_priority(priority)
            # return true for success, you found the object and updated it
            return True
    """ If you arrive at this line, the object didn't exist or 
        it didn't need an update (if you need to distinguish between "object not found" and 
       "object found but didn't update," use an extra flag or nest the != entry.get_priority as you did before"""
    return False

答案 1 :(得分:0)

您的解决方案是正确的,您不需要更改它,因此它不会使用break。没有其他方法可以结束循环,除非它是一个while循环且条件为false或者你在for循环中到达范围的结尾。