我在 python 中创建了一个函数,它将更改对象第一次出现的优先级,但是我无法修复它,因此它只能在不使用中断的情况下第一次出现。在我下面的代码中,我使用了 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
听起来您还想学习如何减少代码长度。一个经验法则是首先专注于使您的代码清晰简洁,这样您就可以尝试找出简化结构的方法。例如,您可以重组和删除冗余分支。你的许多案例只是通过。另外,是的,大学课程说break语句不是很好。为清楚起见,您可能希望使用条件变量来结束循环。在这种情况下,您实际上并不需要这样做,但另一种方法是将代码包装在一个函数中并通过return
ing绕过循环的其余部分,您已经使用了一个函数,因此您可以从该函数返回如果您所做的只是更新一项的优先级(然后退出)。也许您想返回一个状态代码,指示是否找到了一个项目。True
False
)。
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句