如何在python中将列表的hetrogenous列表拼合成单个列表?(How to flatten a hetrogenous list of list into a single list in

编程入门 行业动态 更新时间:2024-10-15 04:22:27
如何在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)

更多推荐

本文发布于:2023-07-28 06:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1301649.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表   中将   如何在   python   single

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!