[ํŒŒ์ด์ฌ] 2์ฐจ์› ๋ฆฌ์ŠคํŠธ๋ฅผ 1์ฐจ์› ๋ฆฌ์ŠคํŠธ๋กœ ๋งŒ๋“ค๊ธฐ

2020. 12. 30. 23:19ใ†Backend/๐Ÿ Python

2์ฐจ์› ๋ฆฌ์ŠคํŠธ๋ฅผ 1์ฐจ์› ๋ฆฌ์ŠคํŠธ์˜ ํ˜•ํƒœ๋กœ ๋งŒ๋“œ๋Š” ๊ฒƒ์„ flatten์ด๋ผ ๋ถ€๋ฅธ๋‹ค.

์ฆ‰ matrix(2์ฐจ์› ๋ฐฐ์—ด)๋ฅผ ๋ฆฌ์ŠคํŠธ(1์ฐจ์› ๋ฐฐ์—ด) ํ˜•ํƒœ๋กœ ๋งŒ๋“œ๋Š” ๊ฒƒ์ด๋‹ค.

 

 

my_list = [[1, 2], [3, 4], [5, 6]]

๋ฐฉ๋ฒ• 1 - sum ํ•จ์ˆ˜

answer = sum(my_list, [])
print(answer)

>>> [1, 2, 3, 4, 5, 6]

 

itertools ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ํ™œ์šฉ

๋ฐฉ๋ฒ• 2 - itertools.chain

print(list(itertools.chain(*board)))

>>> [1, 2, 3, 4, 5, 6]

๋˜ํ•œ, itertools ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์—๋Š” iterableํ•œ ๊ฐ์ฒด๋ฅผ ์—ฐ๊ฒฐํ•˜์—ฌ ๋ฐ˜ํ™˜ํ•˜๋Š” itertools.chain() ํ•จ์ˆ˜๊ฐ€ ์žˆ๋‹ค.

itertools.chain() ๋ฉ”์„œ๋“œ ์ธ์ž์˜ iterable ์›์†Œ๋ฅผ ์—ฐ๊ฒฐํ•˜์—ฌ ๋ฐ˜ํ™˜ํ•ด์ค€๋‹ค.

 

* ๋‹จ, 2์ฐจ์› ๋ฐฐ์—ด ํ˜•ํƒœ๊ฐ€ ๊ทธ๋Œ€๋กœ ๋“ค์–ด๊ฐ€๋ฉด ์•ˆ๋œ๋‹ค. asterisk(*)๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ 2์ฐจ์› ๋ฐฐ์—ด์„ unpackingํ›„ ์›์†Œ๋ฅผ ์—ฐ๊ฒฐํ•ด์ค€๋‹ค.

* list๋กœ ๊ฐ์‹ธ์ง€ ์•Š์œผ๋ฉด hash๊ฐ’๋งŒ ์ถœ๋ ฅ๋œ๋‹ค. ์šฐ๋ฆฌ๊ฐ€ ์›ํ•˜๋Š” ๊ฑด list๊ฒฐ๊ณผ๊ฐ’์ด๊ธฐ์— ๊ผญ list()๋ฅผ ์”Œ์›Œ์ฃผ์ž.

 

๋ฐฉ๋ฒ• 3 - itertools.chain.from_iterable

import itertools
print(list(itertools.chain.from_iterable(board)))

>>> [1, 2, 3, 4, 5, 6]

๋ฐฉ๋ฒ• 2 ์—์„  asterisk ๋ฅผ ์‚ฌ์šฉํ•œ unpacking ๊ณผ์ •์„ ๊ผญ ๊ฑฐ์ณ์•ผํ•œ๋‹ค. ์ด๋Ÿฐ ๊ณผ์ •์ด ๊ท€์ฐฎ๋‹ค๋ฉด, from_iterable() ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

 

 

 

reduce(์ง‘๊ณ„ ํ•จ์ˆ˜, ์ˆœํšŒ ๊ฐ€๋Šฅ ๋ฐ์ดํ„ฐ[, ์ดˆ๊ธฐ๊ฐ’]) # ์ˆœํšŒ ๊ฐ€๋Šฅ ๋ฐ์ดํ„ฐ: iterables

 

๋ฐฉ๋ฒ• 4 - reduce ํ•จ์ˆ˜ (1)

from functools import reduce 
print(list(reduce(lambda x, y: x+y, my_list)))

>>> [1, 2, 3, 4, 5, 6]

 

๋ฐฉ๋ฒ• 5 - reduce ํ•จ์ˆ˜ (2)

operator.add(x, y)๋Š” x+y ํ‘œํ˜„์‹๊ณผ ๋™๋“ฑํ•˜๋‹ค. ์ฆ‰ ์œ„์˜ ๋ฐฉ๋ฒ• 4์˜ lambda x, y: x + y ๊ฐ€ operator.add์˜ ์—ญํ• ์„ ํ•œ๋‹ค.

from functools import reduce 
import operator 
print(list(reduce(operator.add, my_list)))

>>> [1, 2, 3, 4, 5, 6]