Python-提取最内部的列表
刚开始玩弄Python,所以请容忍我:) 假设以下列表包含嵌套列表:Python-提取最内部的列表,python,python-2.7,Python,Python 2.7,刚开始玩弄Python,所以请容忍我:) 假设以下列表包含嵌套列表: [[[[[1, 3, 4, 5]], [1, 3, 8]], [[1, 7, 8]]], [[[6, 7, 8]]], [9]] 在不同的表述中: [ [ [ [ [1, 3, 4, 5] ], [1, 3, 8] ], [ [1, 7,
[[[[[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(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
列表的输出(获取内部(嵌套列表))
:
甚至更短,不带生成器,用于组合生成的列表:
def get_inner(nested):
if all(type(x) == list for x in nested):
return sum(map(get_inner, nested), [])
return [nested]
使用:
使用了isinstance(xs[0],list)
而不是all(xs中x的isinstance(x,list)
,因为没有混合列表/空内部列表
比递归更有效:
result = []
while lst:
l = lst.pop(0)
if type(l[0]) == list:
lst += [sublst for sublst in l if sublst] # skip empty lists []
else:
result.insert(0, l)
对于
[1,3,4,5]]、[1,3,8]]、[1,7,8]]、[6,7,8]]、[9,10]]
和[1,3,4,5]]、[1,3,8]]、[1,7,8]]、[6,7,8]]、[[6,7,8]]、[]
,应该返回什么?感谢您提出的澄清问题:从第一个项目中删除第一个项目时,将永远不会包含空列表或混合类型的列表,插入列表的开头需要O(n)个时间。使用可以提高速度。如果您声称您的解决方案比其他解决方案更高效,请附上小型和大型输入的基准测试。请参阅falsetru的评论,了解其速度慢的原因。
from itertools import chain
def get_inner_lists(xs):
if isinstance(xs[0], list): # OR all(isinstance(x, list) for x in xs)
return chain.from_iterable(map(get_inner_lists, xs))
return xs,
>>> list(get_inner_lists([[[[[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]]
result = []
while lst:
l = lst.pop(0)
if type(l[0]) == list:
lst += [sublst for sublst in l if sublst] # skip empty lists []
else:
result.insert(0, l)