์ด ๊ธ€์€ ์ •๋ฆฌ๋ฅผ ์œ„ํ•ด ๊ฐœ์ธ์ ์ธ ์šฉ๋„๋กœ ์ž‘์„ฑ๋œ ํฌ์ŠคํŠธ์ž…๋‹ˆ๋‹ค. ์ง€์ ๊ณผ ์กฐ์–ธ์€ ์–ธ์ œ๋‚˜ ํ™˜์˜์ž…๋‹ˆ๋‹ค ใ…Žใ…Ž

3 minute read

์ด ๊ธ€์€ ์ •๋ฆฌ๋ฅผ ์œ„ํ•ด ๊ฐœ์ธ์ ์ธ ์šฉ๋„๋กœ ์ž‘์„ฑ๋œ ํฌ์ŠคํŠธ์ž…๋‹ˆ๋‹ค. ์ง€์ ๊ณผ ์กฐ์–ธ์€ ์–ธ์ œ๋‚˜ ํ™˜์˜์ž…๋‹ˆ๋‹ค ใ…Žใ…Ž


Iterable.

๋Œ€์ถฉ list์ฒ˜๋Ÿผ iteration์„ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ๋Š” ๋…€์„์„ ํ†ต์นญ iterable ์ด๋ผ๊ณ  ํ•จ. ๋˜๋Š” for ... in ... ๋กœ ์ˆœํšŒํ•  ์ˆ˜ ์žˆ๋Š” ๋…€์„์ด๋ผ๊ณ  ์ƒ๊ฐํ•ด๋„ ๋  ๋“ฏ.

mylist = [1, 2, 3]
mylist2 = [x * x for x in range(3)] # list comprehension

์ฐธ๊ณ ๋กœ range(n), ์ด ๋…€์„๋„ iterable์ด๋‹ค.


Generator.

generator ์—ญ์‹œ for ... in ...์œผ๋กœ ์ˆœํšŒํ•  ์ˆ˜ ์žˆ์Œ. ๊ทธ๋Ÿฐ๋ฐ ๋ชจ๋“  ๊ฐ’์„ ๋ฉ”๋ชจ๋ฆฌ์— ๋‹ด๊ณ  ์žˆ์ง€ ์•Š๊ณ , ๊ทธ๋•Œ๊ทธ๋•Œ ๊ฐ’์„ ์ƒ์„ฑํ•ด์„œ ๋ฐ˜ํ™˜ํ•จ! ๊ทธ๋ž˜์„œ generator๋ฅผ ์“ธ ๋•Œ๋Š” ํ•œ๋ฒˆ์— ํ•˜๋‚˜์˜ ๊ฐ’๋งŒ ์ˆœํšŒํ•  ์ˆ˜ ์žˆ์Œ!

mygenerator = (x * x for x in range(3)) # tuple comprehension
for i in mygenerator:
  print(i)

list comprehension๊ณผ ๋‹ฌ๋ฆฌ tuple comprehension์˜ ๊ฒฝ์šฐ generator๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ํ–‰๋™ ์ž์ฒด๋Š” iterable๊ณผ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ for ... in ...์„ ํ†ตํ•ด ์ˆœํšŒํ•  ์ˆ˜ ์žˆ๋‹ค.

๊ทธ.๋Ÿฌ.๋‚˜. iteration์„ ๋‘ ๋ฒˆ ์ˆ˜ํ–‰ํ•  ์ˆ˜๋Š” ์—†๋‹ค!! ์ฆ‰, generator๋Š” ํ•œ๋ฒˆ๋งŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๋ง์ด๋‹ค. ๊ทธ๋ž˜์„œ for i in mygenerator๋ฅผ ๋‹ค์‹œ ์‹คํ–‰ํ•ด๋„ ๋‹ค์‹œ๋Š” ์œ„์™€ ๊ฐ™์€ ๊ฒฐ๊ณผ๋ฅผ ์–ป์„ ์ˆ˜ ์—†๋‹ค. ํ•œ๋ฒˆ์œผ๋กœ ๋! ๐Ÿ’ฅ

์ด๋Ÿฐ generator๋ฅผ ํ•จ์ˆ˜๋กœ ๋งŒ๋“ค ์ˆ˜๋„ ์žˆ๋Š”๋ฐ, ์ด ๊ฒฝ์šฐ yield ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

def createGenerator(n):
  for i in range(n):
    yield i * i


Iterable๊ณผ Iterator.

tuple, list, str๊ณผ ๊ฐ™์€ ๋…€์„์€ iterable ์ด๋ผ๊ณ  ํ•œ๋‹ค. ์ด๋Ÿฐ iterable์— iter()๋ฅผ ์”Œ์šฐ๋ฉด ์ด ๋…€์„๋“ค์˜ iterator ์„ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค!!

mytuple = ("apple", "banna", "cherry")
myiter = iter(mytuple)

์‚ฌ์‹ค python์˜ for ... in ... ๊ตฌ๋ฌธ์€ ์ž์ฒด์ ์œผ๋กœ iterator๋ฅผ ์ƒ์„ฑํ•˜๊ณ , ๋ฌธ๋‹จ์˜ ๋์— next()๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๋™์ž‘ํ•œ๋‹ค๊ณ  ํ•œ๋‹ค! ๐Ÿ˜ฒ


Iterable๊ณผ Enumerator.

์•„๋ž˜์˜ ๋‘ ์ฝ”๋“œ๋Š” ๋™์น˜๋‹ค.

# iterable with index
i = 0
for value in myIterable:
  print(i, value)
  i += 1
# iterable with enumerate
for i, value in enumerate(myIterable):
  print(i, value)
for i, value in enumerate(myIterable, start=0):
  print(i, value)

Lambda Function.

JS์˜ ์ต๋ช… ํ•จ์ˆ˜์™€ ๋™์น˜์ž„.

square_fun = lambda x: x*x
exp_fun = lambda x, y: x**y
sign = lambda x: (1, -1)[x < 0] # "x < 0"์˜ ๊ฐ’์„ tuple์˜ idx๋กœ ์‚ฌ์šฉ!

Updated: