简体   繁体   English

python:展平到列表列表但不多了

[英]python: flatten to a list of lists but no more

I have a list of lists which is nested in multiple layers of lists. 我有一个嵌套在多个列表层中的列表列表。

possible inputs: 可能的输入:

[[[[1,2,3] , [a,b,c]]]] or [[[1,2,3] , [a,b,c]]] or [[[1,2,3]] , [[a,b,c]]] [[[[1,2,3] , [a,b,c]]]][[[1,2,3] , [a,b,c]]][[[1,2,3]] , [[a,b,c]]]

when I use flat() it will just flatten everything which is not what I want. 当我使用flat()它会压扁所有不是我想要的东西。

[1,2,3,a,b,c]

What I need instead is 我需要的是

[[1,2,3] , [a,b,c]]

as the final output. 作为最终输出。

My flat definition is below 我的平面定义如下

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))

yields 产量

[[1, 2, 3], ['a', 'b', 'c']]
[[1, 2, 3], ['a', 'b', 'c']]
[[1, 2, 3], ['a', 'b', 'c']]

Replacing: 更换:

if S == []:
    return S

with: 有:

if (not any([isinstance(x,list) for x in S])) :
    return [] if S==[] else [S]

seems to do the trick. 似乎可以做到这一点。

Or: 要么:

if S == []:
    return S
if (not any([isinstance(x,list) for x in S])) :
    return [S]

I see two requirements - detecting when S shouldn't be flattened, and then returning a value that won't be flatten when joined with the rest (ie join with append rather than extend ). 我看到两个要求 - 检测S何时不应该被展平,然后返回一个在与其余部分连接时不会变平的值(即使用append而不是extend )。 My guess is that a list of non-list elements should not be flattened. 我的猜测是,非列表元素列表不应该被展平。

I'm barking up the same tree as unutbu , but in a more confused manner.:) 我和unutbu一样吠叫同一棵树,但是更加混乱。:)

flat() could become flat()可能会成为

def flat(mylist):
    return[val for sublist in mylist for val in sublist]

Then you could call it in a for loop like this 然后你可以像这样在for循环中调用它

while type(mylist[0][0]) is list:
    mylist = flat(my list)

and it will reduce it to your desired output regardless of the number of nested lists 无论嵌套列表的数量如何,它都会将其减少到您想要的输出

[[1, 2, 3], ['a', 'b', 'c']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM