/ 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...
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
#!/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)))
Comments
