๋ฐ์ํ
#ํ์ด์ฌ ๋ฆฌ์คํธ ํผ์น๊ธฐ #ํ์ด์ฌ 2d ๋ฆฌ์คํธ ํผ์น๊ธฐ #python 2d list flatten #python nested list flatten
๋ค์๊ณผ ๊ฐ์ด 2D list๋ฅผ 1D list๋ก ์ ํํ๋ ๋ฐฉ์์ 'flattening'์ด๋ผ๊ณ ํ๋ค
1. itertools์ chain ํจ์ ์ฌ์ฉํ๊ธฐ
import itertools
List_2D = [['a','b','c'],[1,2,3],['d',4,'e']] #List to be flattened
List_flat = list(itertools.chain(*List_2D))
print("Original List:",List_2D)
print("Flattened List:",List_flat)
# print๋ฌธ ์ถ๋ ฅ๊ฒฐ๊ณผ
# Original List: [['a', 'b', 'c'], [1, 2, 3], ['d', 4, 'e']]
# Flattened List: ['a', 'b', 'c', 1, 2, 3, 'd', 4, 'e']
2. functools์ reduce ํจ์์ operator์ iconcat ํจ์ ์ฌ์ฉํ๊ธฐ (1๋ฒ๋ณด๋ค ๋น ๋ฆ)
import functools
import operator
lst_2D = [['a','b','c'],[1,2,3],['d',4,'e']] #List to be flattened
lst_flat = functools.reduce(operator.iconcat, lst_2D, [])
print("Original List:",lst_2D)
print("Flattened List:",lst_flat)
# print ์ถ๋ ฅ๊ฒฐ๊ณผ
# Original List: [['a', 'b', 'c'], [1, 2, 3], ['d', 4, 'e']]
# Flattened List: ['a', 'b', 'c', 1, 2, 3, 'd', 4, 'e']
reference : www.educative.io/edpresso/how-to-flatten-a-list-of-lists-in-python
728x90
๋ฐ์ํ
'Computer Science' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[tmux] ์คํฌ๋กค ๊ฐ๋ฅํ๊ฒ ํ๊ธฐ (0) | 2024.07.24 |
---|---|
[Go] Go๋ฐฐ์ฐ๊ธฐ (1) | 2024.07.24 |
[Firebase] Firebase๋? ์ธ์ ์ด๋์ ์ฌ์ฉํ๋ฉด ์ข์๊ฐ (0) | 2024.01.18 |
[Xcode ์๋ฌ] Error (Xcode): Cycle inside Runner; building could produce unreliable results (ํด๊ฒฐ๋ฒ ํฌํจ โ๏ธ) (3) | 2024.01.05 |
[SQLD] SQLD ์ ํจ๊ธฐ๊ฐ ๋ง๋ฃ ๋ฉ์ถฐ!!!!!! (feat. ํด๊ฒฐ๋ฐฉ๋ฒ) (0) | 2022.04.27 |
[git] Merge and Pull Request (feat. PR ๋ ๋ ค์ฃผ์ธ์~) (0) | 2021.07.31 |
[Xcode] Preview crashed ํ์ (0) | 2021.06.04 |
[Git ํด๋ ์์ฑ] github์์ ํด๋ ์์ฑํ๋ ๋ฐฉ๋ฒ (2) | 2021.04.20 |