Making a flat list out of list of lists in Python -
i wonder whether there shortcut make simple list out of list of lists in python.
i can in loop, maybe there cool "one-liner"? tried reduce, error.
code
l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] reduce(lambda x, y: x.extend(y), l)
error message
traceback (most recent call last): file "<stdin>", line 1, in <module> file "<stdin>", line 1, in <lambda> attributeerror: 'nonetype' object has no attribute 'extend'
flat_list = [item sublist in l item in sublist]
which means:
for sublist in l: item in sublist: flat_list.append(item)
is faster shortcuts posted far. (l
list flatten.)
here corresponding function:
flatten = lambda l: [item sublist in l item in sublist]
for evidence, always, can use timeit
module in standard library:
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item sublist in l item in sublist]' 10000 loops, best of 3: 143 usec per loop $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])' 1000 loops, best of 3: 969 usec per loop $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)' 1000 loops, best of 3: 1.1 msec per loop
explanation: shortcuts based on +
(including implied use in sum
) are, of necessity, o(l**2)
when there l sublists -- intermediate result list keeps getting longer, @ each step new intermediate result list object gets allocated, , items in previous intermediate result must copied on (as few new ones added @ end). (for simplicity , without actual loss of generality) have l sublists of items each: first items copied , forth l-1 times, second items l-2 times, , on; total number of copies times sum of x x 1 l excluded, i.e., i * (l**2)/2
.
the list comprehension generates 1 list, once, , copies each item on (from original place of residence result list) once.
Comments
Post a Comment