list - python lambda for list_of_list collapse -


ok, newbie getting in knots list_of_list collapse.

i figured out can reduce loops below comprehension.

lol = [[0, 1, 2, 3, 4, 50, 51, 52, 53, 54], \        [50, 51, 52, 53, 54], \        [150, 151, 152, 153, 154]]  collapsed_lol = list() innerlist in lol:     item in innerlist:         collapsed_lol.append(item)  collapsed_lol = [item innerlist in lol item in innerlist] 

but tried reduce(lambda) approach , got unstuck. why not work?

collapsed_lol = reduce(lambda a,x: a.extend(x), lol) # traceback (most recent call last): # file "<stdin>", line 1, in <module> # file "<stdin>", line 1, in <lambda> # attributeerror: 'nonetype' object has no attribute 'extend' # lol # [[0, 1, 2, 3, 4, 50, 51, 52, 53, 54, 50, 51, 52, 53, 54], [50, 51, 52, 53, 54], [150, 151, 152, 153, 154]]  # lol[0].append[lol[1]] did occur, stopped. 

if assign lambda variable instead of inside reduce, same, doing lol[0].extend[lol[1]]; return none.

f = lambda a,b: a.extend(b) lst_1 = [0, 1, 2, 3, 4, 5] lst_2 = [50, 51, 52, 53, 54] ret=f(lst_1,lst_2) ret # nothing lst_1 # [0, 1, 2, 3, 4, 5, 50, 51, 52, 53, 54] lst_2 # [50, 51, 52, 53, 54] print f(lst_1,lst_2) # none 

this same behavior in nested reduce contruct.

clearly i'm trying doesn't work, not way lambda's supposed used - can explain none represents, process involved here is? thanks

the function pass reduce has return value of fn(a,b). since extend() returns none, can't use lambda have.

you can force lambda return value changing to:

fn = lambda a,b: a.extend(b) or 

and calling reduce(fn, lol) return value of lists in 'lol' appended together. note though happens. have modified first element of lol summed value. why? because first call reduce() uses first 2 elements of given sequence a , b, calls fn(a,b), , uses returned value a next call, , next element in list b, , on until list exhausted. if written in python like:

def reduce(fn, seq):     seq_iter = iter(seq)     = next(seq_iter)     b in seq_iter:         = fn(a,b)     return 

since extend() updates list in place, repeatedly extend lol[0] element.

you may better off using sum(lol, []) flatten list-of-lists. has memory warts relative making many copies of intermediate lists, short lists simple , gets job done.

if absolutely set on using reduce , don't want modify contents of lol, use reduce(lambda a,b: a+b, lol). generate many intermediate lists, won't modify contents of lol (because when a , b lists, a+b returns new list, doesn't modify in place extend()).


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -