Get An Array Back From An Itertools.chain Object
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
Solution 1:
list
. If you do list(chain)
it should work. But use this just for debugging purposes, it could be inefficient in general.
Solution 2:
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
Post a Comment for "Get An Array Back From An Itertools.chain Object"