在Python中展平列表(任意深度)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Python中展平列表(任意深度)相关的知识,希望对你有一定的参考价值。
Flatten a list of lists (or tuple of tuples, list of tuples, etc.) to any depth of nesting using no mutable objects.
def flat(lst): ''' return a tuple making from all values from the flatten list of lists (or tuple of tuples, etc.) ''' return reduce(lambda l, e: (isinstance(e, list) or isinstance(e, tuple)) and l + flat(e) or l + (e,), lst, ()) assert flat([]) == () assert flat((1,)) == (1,) assert flat([1, 2, 3]) == (1, 2, 3) assert flat([(1,2),[3,4,[5,6]],7,8,(9,(0,))]) == (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
以上是关于在Python中展平列表(任意深度)的主要内容,如果未能解决你的问题,请参考以下文章