[Python] Flattening list of lists

tanky(67)
Published in
#kr
Words
81
Reading
1 min
7y
Listen to this post
~1 min

1. sum()

ex)

iterables = [[1, 2], [3, 4, 5]]
sum(iterables, [ ])
=> [1, 2, 3, 4, 5]

하지만 sum은 많이많이 느리다...

그래서,

2. itertools.chain(*iterables)

3. itertools.chain.from_iterable(iterables)

4. list comprehension

ex)
iterables = [[1, 2], [3, 4, 5]]
[ y for x in iterables for y in x ]
=> [1, 2, 3, 4, 5]



그리고 이보다 더 빠른 건

5. numpy

iterables = [[1, 2], [3, 4]]
testlist = np.array(iterables)

5.1

testlist.reshape(-1)

5.2 -- 이게 5.1보다 좀더 빠름

testlit.flatten()

[Python] Flattening list of lists | Ecency