flatten python lists


/ Published in: Python
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. #!/usr/bin/env python3.2
  2. # Bastian Kruck ([email protected])
  3. # 11.7.2011
  4.  
  5. """
  6. 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...
  7. """
  8.  
  9. import functools
  10.  
  11. def reductor(x,y):
  12. return flatten(x) + flatten(y)
  13.  
  14. def flatten(l):
  15. if isinstance(l,list):
  16. l = functools.reduce(reductor, l)
  17. if isinstance(l, list):
  18. return l
  19. return [l]
  20.  
  21. if __name__=="__main__":
  22. print("testing myself...is this right?")
  23. tests = [[3], [[4]], [2,3], [[3],4] , [[[[4],[5,[3]]]],4,[55,2,]]]
  24. for test in tests:
  25. print("%s \t\t\t=>\t %s" % (test, flatten(test)))

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.