1 ๋ถ„ ์†Œ์š”

Python map ํ•จ์ˆ˜๊ฐ€ ๋ญ˜๊นŒ?

map์€ ๋ฆฌ์ŠคํŠธ์˜ ์š”์†Œ๋ฅผ ์ง€์ •๋œ ํ•จ์ˆ˜๋กœ ์ฒ˜๋ฆฌํ•ด์ฃผ๋Š” ํ•จ์ˆ˜๋‹ค.
map์€ ์›๋ณธ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ณ€๊ฒฝํ•˜์ง€ ์•Š๊ณ  ์ƒˆ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.

map ๊ตฌ์กฐ์™€ ์˜ˆ์ œ

map(function, iterable)
mapํ•จ์ˆ˜์˜ ๊ธฐ๋ณธ ๊ตฌ์กฐ๋Š” ์œ„์™€ ๊ฐ™๋‹ค.

map์„ ๋ฆฌ์ŠคํŠธ, ํŠœํ”Œ์— ์ ์šฉํ•ด๋ณด์ž.
list(map(function, list))
tuple(map(function, tuple))

[์ ์šฉ์˜ˆ์ œ1]

a = [1, 2, 3, 4, 5]
for i in range(len(a)):
    a[i] = int(a[i])
...

print(a)

[์ ์šฉ์˜ˆ์ œ1-๊ฒฐ๊ณผ]

> [1, 2, 3, 4]


[์ ์šฉ์˜ˆ์ œ2]

a = [1, 2, 3, 4, 5]
a = list(map(int, a))
print(a)

[์ ์šฉ์˜ˆ์ œ2- ๊ฒฐ๊ณผ]

> [1, 2, 3, 4]

๋ฆฌ์ŠคํŠธ๋ฅผ mapํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด ํ•œ ์ค„๋กœ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.

[๊ทธ๋ฆผ ์„ค๋ช…]
แ„‰แ…ณแ„แ…ณแ„…แ…ตแ†ซแ„‰แ…ฃแ†บ 2023-03-06 แ„‹แ…ฉแ„Œแ…ฅแ†ซ 9 57 48

map์€ ๋ฆฌ์ŠคํŠธ์—๋งŒ ์‚ฌ์šฉ๊ฐ€๋Šฅํ•œ ๊ฒƒ์ด ์•„๋‹˜!

์‚ฌ์‹ค map์€ ๋ฆฌ์ŠคํŠธ ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ๋ชจ๋“  ๋ฐ˜๋ณต ๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด๋ฅผ ๋„ฃ์„ ์ˆ˜ ์žˆ๋‹ค.
[์˜ˆ์ œ]

a = list(map(str, range(10)))
print(a)
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

input()์— map์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค!

input()์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ž…๋ ฅ๋ฐ›๊ณ , split()์œผ๋กœ ์—ฌ๋Ÿฌ ๊ฐœ๋ฅผ ์ž…๋ ฅ๋ฐ›์„ ์ˆ˜ ์žˆ์—ˆ๋‹ค.
input().split()์˜ ๊ฒฐ๊ณผ๋ฅผ ์ •์ˆ˜, ์‹ค์ˆ˜๋กœ ๋ณ€ํ™˜ํ•  ๋•Œ๋„ map์„ ์‚ฌ์šฉํ•ด ๋ณ€ํ™˜ํ•  ์ˆ˜ ์žˆ๋‹ค.
์–ด๋–ป๊ฒŒ ๊ฐ€๋Šฅํ• ๊นŒ?
input().split()์˜ ๊ฒฐ๊ณผ๊ฐ€ ๋ฌธ์ž์—ด ๋ฆฌ์ŠคํŠธ๋ผ์„œ ๊ฐ€๋Šฅํ•˜๋‹ค.
[์˜ˆ์ œ1]

a = map(int, input().split())   # ์ž…๋ ฅ: 10 20
print(a)    # <map object at 0x03DFB0D0>
print(list(a))  # [10, 20]


์‚ฌ์‹ค map์ด ๋ฐ˜ํ™˜ํ•˜๋Š” ๋งต ๊ฐ์ฒด๋Š” ์ดํ„ฐ๋ ˆ์ดํ„ฐ๋ผ์„œ ๋ณ€์ˆ˜ ์—ฌ๋Ÿฌ ๊ฐœ์— ์ €์žฅํ•˜๋Š” ์–ธํŒจํ‚น(unpacking)์ด ๊ฐ€๋Šฅํ•˜๋‹ค!

์–ธํŒจํ‚น์ด ๋ญ”๋ฐ?
ํ•œ ๋ณ€์ˆ˜์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ๊ฐ์˜ ๋ณ€์ˆ˜๋กœ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ โ†’ ๋ฌถ์ธ ๊ฑธ ํ‘ผ๋‹ค!

[์˜ˆ์ œ2]

x = input().split()
m = map(int, x)
a, b = m    # ๋งต ๊ฐ์ฒด๋Š” ๋ณ€์ˆ˜ ์—ฌ๋Ÿฌ ๊ฐœ ์ €์žฅํ•  ์ˆ˜ ์žˆ์Œ

์ฐธ๊ณ ์ž๋ฃŒ

https://dojang.io/mod/page/view.php?id=2286
https://roi-data.com/entry/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%ED%8C%A8%ED%82%B9-packing-%EC%96%B8%ED%8C%A8%ED%82%B9-unpacking

ํƒœ๊ทธ:

์นดํ…Œ๊ณ ๋ฆฌ:

์—…๋ฐ์ดํŠธ:

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ