我有一个列表列表,它嵌套在多层列表中。
可能的输入:
[[[[1,2,3] , [a,b,c]]]]
或 [[[1,2,3] , [a,b, c]]]
或 [[[1,2,3]] , [[a,b,c]]]
当我使用 flat()
时,它只会展平所有不是我想要的东西。
[1,2,3,a,b,c]
我需要的是
[[1,2,3] , [a,b,c]]
作为最终输出。
我的平面定义如下
def flat(S):
if S == []:
return S
if isinstance(S[0], list):
return flat(S[0]) + flat(S[1:])
return S[:1] + flat(S[1:])
最佳答案
import collections
def is_listlike(x):
return isinstance(x, collections.Iterable) and not isinstance(x, basestring)
def flat(S):
result = []
for item in S:
if is_listlike(item) and len(item) > 0 and not is_listlike(item[0]):
result.append(item)
else:
result.extend(flat(item))
return result
tests = [ [[[[1,2,3] , ['a','b','c']]]],
[[[1,2,3] , ['a','b','c']]],
[[[1,2,3]] , [['a','b','c']]] ]
for S in tests:
print(flat(S))
产量
[[1, 2, 3], ['a', 'b', 'c']]
[[1, 2, 3], ['a', 'b', 'c']]
[[1, 2, 3], ['a', 'b', 'c']]
关于python:扁平化为列表列表但仅此而已,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27652422/