In [25]:
list_of_lists = [[1, 2], [3, 4]]
In [30]:
result1 = []
for x in list_of_lists:
for j in x :
result1.append(j)
print(result1)
In [31]:
[y for x in list_of_lists for y in x]
# 이해하기 어려우면 아래를 참고!
Out[31]:
In [32]:
for x in list_of_lists:
print(x)
In [33]:
for x in list_of_lists:
for y in x:
print(y)
In [35]:
result = []
for item in list_of_lists:
result.extend(item)
print(result)
In [1]:
def chain(*iterables):
# chain('ABC', 'DEF') --> ['A', 'B', 'C', 'D', 'E', 'F']
for it in iterables:
for element in it:
yield element
In [3]:
import itertools
list(itertools.chain(list_of_lists))
Out[3]:
In [5]:
# 앞에 *(asterisk)을 붙여주면 우리가 원하는 값이 나옴
list(itertools.chain(*list_of_lists))
Out[5]:
In [8]:
# from_iterble을 사용하면 더 쉽게 사용가능
list(itertools.chain.from_iterable(list_of_lists))
Out[8]:
In [36]:
sum(list_of_lists, [])
Out[36]:
In [38]:
import numpy as np
list_of_lists = [[x, 0] for x in range(10000)]
In [41]:
n_lol = np.array(list_of_lists)
Out[41]:
In [45]:
n_lol.reshape(-1)
# 1000000 loops, best of 3: 820 ns per loop
Out[45]:
In [46]:
n_lol.flatten()
# 1000000 loops, best of 3: 1 µs per loop
Out[46]:
In [47]:
from itertools import chain
list_of_lists = [[x, 0] for x in range(10000)]
%timeit list(chain(*list_of_lists))
# 1000 loops, best of 3: 491 µs per loop
%timeit list(chain.from_iterable(list_of_lists))
# 1000 loops, best of 3: 429 µs per loop
%timeit [y for x in list_of_lists for y in x]
# 1000 loops, best of 3: 725 µs per loop
%timeit sum(list_of_lists, [])
# 1 loop, best of 3: 211 ms per loop
In [ ]: