这是参考答案的改编,以使用内部函数和单个函数
set。它还使用递归为问题中包含的样本输入生成预期输出。它避免了使每个叶子都经过整个调用堆栈。
from typing import Any, Setdef leaves(struct: Any) -> Set[Any]: """Return a set of leaf values found in nested dicts and lists excluding None values.""" # Ref: https://stackoverflow.com/a/59832594/ values = set() def add_leaves(struct_: Any) -> None: if isinstance(struct_, dict): for sub_struct in struct_.values(): add_leaves(sub_struct) elif isinstance(struct_, list): for sub_struct in struct_: add_leaves(sub_struct) elif struct_ is not None: values.add(struct_) add_leaves(struct) return values
信用:堆溢出的建议



