Is there a simple function that can extract all numbers from a list of lists. For example:
l = [ [1,2], [1, 5], [2] ] -> [1,2,1,5,2]
i would like to avoid using loops or list comprehensions.
Is there a simple function that can extract all numbers from a list of lists. For example:
l = [ [1,2], [1, 5], [2] ] -> [1,2,1,5,2]
i would like to avoid using loops or list comprehensions.
I would like to avoid using loops or list comprehensions.
You can use itertools.chain
method in combination with Extended iterable unpacking
operator.
chain
method makes an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted.
import itertools
merged = list(itertools.chain(*l))
Output
[1,2,1,5,2]
Another approach is to use reduce
function.
l = reduce(lambda x,y: x+y,l)
Use list comprehension
:
>>> x = [j for i in l for j in i]
[1, 2, 1, 5, 2]
Using itertools.chain
Demo:
import itertools
l = [ [1,2], [1, 5], [2] ]
print(list(itertools.chain(*l))) #or print(list(itertools.chain.from_iterable(l)))
Output:
[1, 2, 1, 5, 2]