Python拼合列表(但并非始终如此) [英] Python flatten list (but not all the way)
本文介绍了Python拼合列表(但并非始终如此)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表列表...
I have a list of lists of lists...
A = [ [[1,3]], [[3,5], [4,4], [[5,3]]] ]
以下函数输出[1, 3, 3, 5, 4, 4, 5, 3]
def flatten(a):
b = []
for c in a:
if isinstance(c, list):
b.extend(flatten(c))
else:
b.append(c)
return b
但是,我想在最后一级停止展平,以便得到[ [1,3], [3,5], [4,4], [5,3] ]
However, I want to stop flattening on the last level so that I get [ [1,3], [3,5], [4,4], [5,3] ]
推荐答案
您可以在展平前测试包含的列表:
You could test for contained lists before flattening:
def flatten(a):
b = []
for c in a:
if isinstance(c, list) and any(isinstance(i, list) for i in c):
b.extend(flatten(c))
else:
b.append(c)
return b
演示:
>>> def flatten(a):
... b = []
... for c in a:
... if isinstance(c, list) and any(isinstance(i, list) for i in c):
... b.extend(flatten(c))
... else:
... b.append(c)
... return b
...
>>> A = [ [[1,3]], [[3,5], [4,4], [[5,3]]] ]
>>> flatten(A)
[[1, 3], [3, 5], [4, 4], [5, 3]]
这试图在情况下尽可能高效; any()
仅需要测试,直到找到列表为止,而不是所有元素.
This tries to be as efficient as can be under the circumstances; any()
only needs to test until a list is found, not all elements.
这篇关于Python拼合列表(但并非始终如此)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文