יום שישי, 21 ביוני 2013

Making a flat list out of list of lists in Python

 

I have found the following ways to flatten a list in python

  1: import timeit 
  2: import itertools
  3: 
  4: def reduce(function, iterable, initializer=None):
  5:     it = iter(iterable)
  6:     if initializer is None:
  7:         try:
  8:             initializer = next(it)
  9:         except StopIteration:
 10:             raise TypeError('reduce() of empty sequence with no initial value')
 11:     accum_value = initializer
 12:     for x in it:
 13:         accum_value = function(accum_value, x)
 14:     return accum_value
 15: 
 16: 
 17: myList =[['a',2,3],[4,5,6], ['zvika'], [(1,5),8,9]]*2
 18: 
 19: Way1 = [item for sublist in myList for item in sublist]
 20: 
 21: print ( Way1 )
 22: 
 23: Way2 = sum(myList, [])
 24: 
 25: print ( Way2 )
 26: 
 27: Way3 = reduce(lambda x,y: x+y,myList)
 28: 
 29: print ( Way3 )
 31: Way4 = list(itertools.chain.from_iterable(myList))
 32: 
 33: print ( Way4)
 34: 
 35: TimeTest =
 30: 
 timeit.Timer(
 36:         'sum(l, [])',
 37:         'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]]'
 38:     ).timeit()
 39: 
 40: print ( TimeTest )

The first way list inside a list.
The second based on a simple explaining :
Just contact one list to the other. 


  1: l = [['Add my'],['and me']]
  2: 
  3: Way2 = sum(l, [])
  4: 
  5: print (Way2)

The 3 way is base one the python reduce function (similar to the sum)
The 4 use the itertools chain method
Note the timeit is a util that helps to measure performance of a code
Resources:
http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python

אין תגובות:

הוסף רשומת תגובה