Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = [[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.

like image 641
zkurtz Avatar asked Feb 12 '23 14:02

zkurtz


2 Answers

list. If you do list(chain) it should work. But use this just for debugging purposes, it could be inefficient in general.

like image 182
spalac24 Avatar answered Feb 15 '23 23:02

spalac24


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
like image 45
Ashwini Chaudhary Avatar answered Feb 15 '23 23:02

Ashwini Chaudhary