Python - 提取最内部的列表 [英] Python - Extracting inner most lists
问题描述
刚开始玩 Python,所以请耐心等待 :)
假设以下列表包含嵌套列表:
[[[[[[1, 3, 4, 5]], [1, 3, 8]], [[1, 7, 8]]], [[[6, 7, 8]]], [9]]
在不同的表示中:
<预><代码>[[[[[1, 3, 4, 5]],[1, 3, 8]],[[1, 7, 8]]],[[[6, 7, 8]]],[9]]您将如何提取这些内部列表,以便返回具有以下形式的结果:
[[1, 3, 4, 5], [1, 3, 8], [1, 7, 8], [6, 7, 8], [9]]
非常感谢!
编辑(感谢@falsetru):
空的内部列表或混合类型列表永远不会成为输入的一部分.
这似乎可行,假设没有像 [1,2,[3]]
这样的混合"列表:
def get_inner(嵌套):if all(type(x) == list for x innested):对于嵌套中的 x:对于 get_inner(x) 中的 y:产量 y别的:产量嵌套
list(get_inner(nested_list))
的输出:
[[1, 3, 4, 5], [1, 3, 8], [1, 7, 8], [6, 7, 8], [9]]
或者更短,没有生成器,使用 sum
组合结果列表:
def get_inner(嵌套):if all(type(x) == list for x innested):返回总和(地图(get_inner,嵌套),[])返回 [嵌套]
Just started toying around with Python so please bear with me :)
Assume the following list which contains nested lists:
[[[[[1, 3, 4, 5]], [1, 3, 8]], [[1, 7, 8]]], [[[6, 7, 8]]], [9]]
In a different representation:
[
[
[
[
[1, 3, 4, 5]
],
[1, 3, 8]
],
[
[1, 7, 8]
]
],
[
[
[6, 7, 8]
]
],
[9]
]
How would you go about extracting those inner lists so that a result with the following form would be returned:
[[1, 3, 4, 5], [1, 3, 8], [1, 7, 8], [6, 7, 8], [9]]
Many thanks!
EDIT (Thanks @falsetru):
Empty inner-list or mixed type lists will never be part of the input.
This seems to work, assuming no 'mixed' lists like [1,2,[3]]
:
def get_inner(nested):
if all(type(x) == list for x in nested):
for x in nested:
for y in get_inner(x):
yield y
else:
yield nested
Output of list(get_inner(nested_list))
:
[[1, 3, 4, 5], [1, 3, 8], [1, 7, 8], [6, 7, 8], [9]]
Or even shorter, without generators, using sum
to combine the resulting lists:
def get_inner(nested):
if all(type(x) == list for x in nested):
return sum(map(get_inner, nested), [])
return [nested]
这篇关于Python - 提取最内部的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!