python delete empty sub lists of list -


this question has answer here:

i want delete empty sub list, ways failed, other ways successful. why ? worry way:

data=[[],[],[],[],[]] rows in data:     if len(rows)==0:        list.remove(rows) print data 

the result [[],[]].it isn't expected result []

the correct way(my friend tell me,thank him):

list = [[],[],[],[],[]] a=list(filter(lambda x: [] != x, list)) print 

the result expected empty list []

avoid iterating on list while doing changes on it:

data=[[],[],[],[],[]] rows in data:     if len(rows)==0:        data.remove(rows) print data 

instead, create new list:

>>> lst = [] >>> data = [[],[],[],[1,2,3]] >>>  >>> rows in data:         if rows: #if rows not empty list             lst.append(rows)   >>> lst [[1, 2, 3]] >>>  

same did filter creates new object:

>>> lst = [[],[],[],[1,2,3],[1,],[], [4,5,6],[7]] >>> lst = filter(list.__len__,lst) >>> lst [[1, 2, 3], [1], [4, 5, 6], [7]] 

edit:

after doing profiling, got following resutls:

>>> import timeit >>> timeit.timeit('filter(list.__len__, lst)', setup='lst=[[],[],[],[1,2,3],[1,],[], [4,5,6],[7]]', number=1000000) 1.03789886128774 >>> >>> timeit.timeit('filter(lambda x:x, lst)', setup='lst=[[],[],[],[1,2,3],[1,],[], [4,5,6],[7]]', number=1000000) 1.0035609489573218 >>> >>> timeit.timeit('filter(none, lst)', setup='lst=[[],[],[],[1,2,3],[1,],[], [4,5,6],[7]]', number=1000000) 0.4335933814062045 >>> >>> timeit.timeit('[l l in lst if l]', setup='lst=[[],[],[],[1,2,3],[1,],[], [4,5,6],[7]]', number=1000000) 0.41073885410420985 

Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -