如何在python中将列表的hetrogenous列表拼合成单个列表?(How to flatten a hetrogenous list of list into a single list in python?)
我有一个对象列表,其中对象可以是列表或标量。 我想要一个只有标量的扁平列表。 例如:
L = [35,53,[525,6743],64,63,[743,754,757]] outputList = [35,53,525,6743,64,63,743,754,757]PS此问题中的答案不适用于异构列表。 在Python中展开浅层列表
I have a list of objects where objects can be lists or scalars. I want an flattened list with only scalars. Eg:
L = [35,53,[525,6743],64,63,[743,754,757]] outputList = [35,53,525,6743,64,63,743,754,757]P.S. The answers in this question does not work for heterogeneous lists. Flattening a shallow list in Python
最满意答案
这是一个相对简单的递归版本,它将使列表的深度变平
l = [35,53,[525,6743],64,63,[743,754,757]] def flatten(xs): result = [] if isinstance(xs, (list, tuple)): for x in xs: result.extend(flatten(x)) else: result.append(xs) return result print flatten(l)Here is a relatively simple recursive version which will flatten any depth of list
l = [35,53,[525,6743],64,63,[743,754,757]] def flatten(xs): result = [] if isinstance(xs, (list, tuple)): for x in xs: result.extend(flatten(x)) else: result.append(xs) return result print flatten(l)更多推荐
发布评论