问题描述
我有一个小问题,我缺乏一些Python经验.假设有一个列表:
I have a small problem where I lack quite some Python experience.Assuming a list:
list=[[40, 20, 45, 40], [[20, 10, 10, 30, 45, 20], [30, 20, 20, 30]]]
我想做我称之为部分展平"的事情,因为预期的输出是:
I want to do something I call 'partial flattening' because the expected output is:
[[40, 20, 45, 40], [20, 10, 10, 30, 45, 20], [30, 20, 20, 30]]
在list
的长度为2
之前发出通知,而预期输出的长度为3
.问题是我事先不知道list
中的哪个元素嵌套更深一层.
Notice before the lentgh of list
was 2
while the expected output has length of 3
. The problem is that I don't know in advance which element from list
is nested one layer deeper.
此答案以及其他许多问题并没有多大帮助,因为扁平化已远远超过了.在问题之后的输出是:
This answer and many others didn't help much, because the flattening goes to far. Following the question the output is:
list=[40, 20, 45, 40, [20, 10, 10, 30, 45, 20], [30, 20, 20, 30]]
(请注意列表中前4个元素的缺失括号.
(notice the missing brackets for the first 4 elements from the list.
推荐答案
您可以创建一个递归函数,测试all
内部元素是否为列表.如果是这样,则递归地应用该算法,否则产生列表本身.
You can create a recursive function, testing whether all
the inner elements are lists. If so, recursively apply the algorithm, otherwise yield the list itself.
def inner_lists(lst):
if all(isinstance(x, list) for x in lst):
for inner in lst:
for x in inner_lists(inner):
yield x
else:
yield lst
>>> lst = [[40, 20, 45, 40], [[20, 10, 10, 30, 45, 20], [30, 20, 20, 30]]]
>>> list(inner_lists(lst))
[[40, 20, 45, 40], [20, 10, 10, 30, 45, 20], [30, 20, 20, 30]]
或使用yield from
(Python 3.3和更高版本):
Or using yield from
(Python 3.3 and later):
def inner_lists(lst):
if all(isinstance(x, list) for x in lst):
yield from (x for inner in lst for x in inner_lists(inner))
else:
yield lst
或者没有发电机:
def inner_lists(lst):
if all(isinstance(x, list) for x in lst):
return [x for inner in lst for x in inner_lists(inner)]
else:
return [lst]
这篇关于部分列表Python中的拼合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!