[英]Trying to get the old age level of a person from family dictionary
我正在尝试从这本字典中获取一个人的老年级别:
d = {'Sıdıka': [{'Aziz': [{'Ahmet': [{'Kuzey': []}]}, {'Öznur': [{'Elif': []}, {'Yiğit': []}]}, {'İlknur': [{'Nurullah': []}, {'Büşra': []}]}, {'İlker': [{'Melih': []}]}]}]}
“Sıdıka”是最年长的一个,我想确定她的级别(即 3(例如,“Sıdıka”是“Kuzey”的父亲、父亲、母亲。等于 3))。
我怎样才能做到这一点?
我试过:递归,但不知道怎么做。
我的尝试:
def new(self,dict,count,max):
for i in dict:
print(dict[i])
if len(dict[i])!=0:
for i in dict[i]:
self.new(self,i,count,max)
count+=1
print(count)
else:
return count
这是一条语句中的简单递归(假设d
是输入字典)。
您可以取消注释打印以查看其工作原理。
def level(d, lvl=0):
#print(f'level {lvl}:', d)
return max((lvl, *(level(l, lvl=lvl+1)
for v in d.values()
for l in v)
))
level(d)
Output: 3
我想我得到了解决方案:
self.max_= 0
def new(self,dict,count):
for i in dict:
print(dict[i])
if len(dict[i])!=0:
for i in dict[i]:
print(self.max_)
self.new(self,i,count)
count+=1
# print(count)
else:
if count>self.max_:
self.max_=count
return self.max_
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.