프로그래밍 언어ㅤ/ㅤPython

중첩 리스트 flatten 하기

다음과 같은 2차원의 Nested List가 있다고 해보자

nestedList = [[8, 5, 7], [5], [7]]

이를 1차원 리스트로 다음과 같이 바꾸고 싶다

[8, 5, 7, 5, 7]

for 문으로 extend하는 방법 등이 있겠으나 생략한다

 

방법 1. itertools.chain( )

- 인자로 받은 iterator들의 원소를 연결하여 반환하는 함수

- 하나의 리스트만 던져주는 경우, 리스트 앞에 * 를 붙여주어야 한다

list(itertools.chain(*nestedList))

 

방법 2. itertools.chain.from_iterable( )

- 하나의 iterator만 넣어줘도 넘겨준다

list(itertools.chain.from_iterable(nestedList))

 

방법 3. List Comprehension

- for x in nestedList 구문이 먼저 해석되어 nestedList의 element들이 각각 x에 들어간다

- y for y in x 구문이 해석되어 각각의 x에 들어있는 element들이 y로 조회되고 최종적으로 y로 이루어진 1차원 리스트가 생성된다

[y for x in nestedList for y in x]

 

방법 4. sum( )

- 속도가 매우 느린편이다

sum(nestedList, [])