Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: flatten to a list of lists but no more

Tags:

python

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

when I use flat() it will just flatten everything which is not what I want.

[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:])
like image 751
user299709 Avatar asked Dec 26 '14 03:12

user299709


People also ask

How do you make a list of lists flat listed?

Flattening a list of lists entails converting a 2D list into a 1D list by un-nesting each list item stored in the list of lists - i.e., converting [[1, 2, 3], [4, 5, 6], [7, 8, 9]] into [1, 2, 3, 4, 5, 6, 7, 8, 9] .


2 Answers

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']]
like image 176
unutbu Avatar answered Oct 22 '22 13:10

unutbu


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 (i.e. join with append rather than 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.:)

like image 44
hpaulj Avatar answered Oct 22 '22 13:10

hpaulj