Return to Snippet

Revision: 48875
at July 12, 2011 07:56 by abstraktor


Updated Code
#!/usr/bin/env python3.2
# Bastian Kruck ([email protected])
# 11.7.2011

"""
        use flatten to reduce a given list to non-list elements. All elements that are no list will be kept and the lists will be expanded...
"""

import functools

def reductor(x,y):
        return flatten(x) + flatten(y)

def flatten(l):
        if isinstance(l,list):
                l = functools.reduce(reductor, l)
                if isinstance(l, list):
                        return l
        return [l]

if __name__=="__main__":
        print("testing myself...is this right?")
        tests =  [[3], [[4]], [2,3], [[3],4] , [[[[4],[5,[3]]]],4,[55,2,]]]
        for test in tests:
                print("%s \t\t\t=>\t  %s" % (test, flatten(test)))

Revision: 48874
at July 12, 2011 07:56 by abstraktor


Initial Code
#!/usr/bin/env python3.2
# Bastian Kruck
# 11.7.2011

"""
        use flatten to reduce a given list to non-list elements. All elements that are no list will be kept and the lists will be expanded...
"""

import functools

def reductor(x,y):
        return flatten(x) + flatten(y)

def flatten(l):
        if isinstance(l,list):
                l = functools.reduce(reductor, l)
                if isinstance(l, list):
                        return l
        return [l]

if __name__=="__main__":
        print("testing myself...is this right?")
        tests =  [[3], [[4]], [2,3], [[3],4] , [[[[4],[5,[3]]]],4,[55,2,]]]
        for test in tests:
                print("%s \t\t\t=>\t  %s" % (test, flatten(test)))

Initial URL

                                

Initial Description
use flatten to reduce a given list to non-list elements. All elements that are no list will be kept and the lists will be expanded...

Initial Title
flatten python lists

Initial Tags
list

Initial Language
Python