Suppose I have list_of_numbers = [[1, 2], [3], []]
and I want the much simpler object list object x = [1, 2, 3]
.
Following the logic of this related solution, I do
list_of_numbers = [[1, 2], [3], []]
import itertools
chain = itertools.chain(*list_of_numbers)
Unfortunately, chain
is not exactly what I want because (for instance) running chain
at the console returns <itertools.chain object at 0x7fb535e17790>
.
What is the function f
such that if I do x = f(chain)
and then type x
at the console I get [1, 2, 3]
?
Update: Actually the result I ultimately need is array([1, 2, 3])
. I'm adding a line in a comment on the selected answer to address this.
list
. If you do list(chain)
it should work. But use this just for debugging purposes, it could be inefficient in general.
If your ultimate goal is to get a Numpy array then you should use numpy.fromiter
here:
>>> import numpy as np
>>> from itertools import chain
>>> list_of_numbers = [[1, 2], [3], []]
>>> np.fromiter(chain(*list_of_numbers), dtype=int)
array([1, 2, 3])
>>> list_of_numbers = [[1, 2]*1000, [3]*1000, []]*1000
>>> %timeit np.fromiter(chain(*list_of_numbers), dtype=int)
10 loops, best of 3: 103 ms per loop
>>> %timeit np.array(list(chain(*list_of_numbers)))
1 loops, best of 3: 199 ms per loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With