Posted By

abstraktor on 07/12/11

flatten python lists

/ Published in: Python

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

```#!/usr/bin/env python3.2# Bastian Kruck ([email protected]
/* <![CDATA[ */!function(){try{var t="currentScript"in document?document.currentScript:function(){for(var t=document.getElementsByTagName("script"),e=t.length;e--;)if(t[e].getAttribute("cf-hash"))return t[e]}();if(t&&t.previousSibling){var e,r,n,i,c=t.previousSibling,a=c.getAttribute("data-cfemail");if(a){for(e="",r=parseInt(a.substr(0,2),16),n=2;a.length-n;n+=2)i=parseInt(a.substr(n,2),16)^r,e+=String.fromCharCode(i);e=document.createTextNode(e),c.parentNode.replaceChild(e,c)}}}catch(u){}}();/* ]]> */)# 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)))```