广度优先,无需递归,它也适用于其他序列类型:
from collections import Sequencefrom itertools import chain, countdef depth(seq): for level in count(): if not seq: return level seq = list(chain.from_iterable(s for s in seq if isinstance(s, Sequence)))
相同的想法,但内存消耗少得多:
from collections import Sequencefrom itertools import chain, countdef depth(seq): seq = iter(seq) try: for level in count(): seq = chain([next(seq)], seq) seq = chain.from_iterable(s for s in seq if isinstance(s, Sequence)) except StopIteration: return level



