我有一个名为items 的对象列表。每个对象都有一个属性 state 和一个属性 children,这是另一个对象列表。每个子对象还有一个名为state 的属性。我想知道的是每个项目及其子项是否都处于快乐或快乐状态。
我对所有人都做了这个(只分析了项目的状态):
if all(item.state in ['happy', 'cheerful'] for item in items):
pass
我想知道哪种方法不仅对元素而且对 child 也能做到同样的事情。
最佳答案
你在这里寻找一些递归:
def is_happy(items):
return all(item.state in ['happy', 'cheerful'] for item in items) and all(is_happy(item.childs) for item in items)
正如@tobias_k 指出的那样,这应该更快,因为它只在项目上迭代一次:
def is_happy(items):
return all(item.state in ['happy', 'cheerful'] and is_happy(item.childs) for item in items)
它至少更具可读性。
如果您只有两层对象,一个简单的 for 也可以解决问题。
def is_happy(items):
happy_children = True
for item in items:
if any(child.state not in ['happy', 'cheerful'] for child in item):
happy_children = False
break
return all(item.state in ['happy', 'cheerful'] for item in items) and happy_children
关于python - 是否可以嵌套所有功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27484771/