嗨,我需要有關此功能的幫助:
def order_of_succession(self, alive: Set[int], succesors: Optional[List[List[int]]] = None, order: int = 1) -> Dict[int, int]:
if succesors is None:
succesors = []
for child in self.children:
temp = []
if child.pid in alive:
temp.append(child.birth_year)
temp.append(order)
temp.append(child.pid)
succesors.append(temp)
child.order_of_succession(alive, succesors, order 1)
succesors = sorted(succesors, key=lambda x: (x[0], x[1]))
succesion = {}
for elem in succesors:
succesion[elem[2]] = elem[1]
return succesion
我唯一的問題是,每次在一個子訂單上完成遞回時,都會更改回已檢查的第一個子訂單的起始訂單。這是該函式的輸出:
{127: 1, 290: 1, 561: 2, 490: 2, 611: 2, 702: 2, 390: 3, 590: 3, 106: 4, 429: 4, 1000: 4, 101: 4, 898: 4, 253: 5}
每次呼叫函式時我都需要增加訂單,但我不知道該怎么做。感謝任何幫助。
uj5u.com熱心網友回復:
沒有什么好方法可以用當前的遞回 API 做您想做的事情,因為您無法輕松回傳更新的內容order(因為您已經回傳了其他內容)。但是,如果您進行更改,使遞回函式成為主函式的輔助函式,則可以使用非區域變數來正確處理它:
def order_of_succession(self, alive: Set[int]) -> Dict[int, int]:
successors: List[List[int]] = [] # both of these variables will be updated in helper
order = 1
def helper(person):
nonlocal order # this lets us modify order
for child in person.children:
if child.pid in alive:
successors.append([child.birth_year, order, child.pid])
order = 1 # which we do here
helper(child)
helper(self)
succesors = sorted(succesors, key=lambda x: (x[0], x[1])) # the rest is unchanged
succesion = {}
for elem in succesors:
succesion[elem[2]] = elem[1]
return succesion
這不是挺你問什么,因為我只更新了order生活的孩子。如果您希望即使在您對非生命孩子進行遞回時順序也會增加,您可以將該order = 1行移到if陳述句之外。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/375108.html
