Computer Science

[python list] ํŒŒ์ด์ฌ ๋ฆฌ์ŠคํŠธ ์•ˆ ๋ฆฌ์ŠคํŠธ ํŽผ์น˜๊ธฐ_how to flatten a list of lists in python

_cactus 2021. 4. 22. 09:53
๋ฐ˜์‘ํ˜•

#ํŒŒ์ด์ฌ ๋ฆฌ์ŠคํŠธ ํŽผ์น˜๊ธฐ #ํŒŒ์ด์ฌ 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
๋ฐ˜์‘ํ˜•