πŸ„πŸ» 파이썬 μ œλ„ˆλ ˆμ΄ν„°

may_soouuΒ·2021λ…„ 1μ›” 1일
0
post-thumbnail

이전에 μ œλ„ˆλ ˆμ΄ν„°λ₯Ό μ•„μ£Ό 잠깐 μ •λ¦¬ν•˜κ³  λ„˜μ–΄κ°”λŠ”λ° μ œλŒ€λ‘œ κ³΅λΆ€ν•˜κ³ μž λ‹€μ‹œ μ •λ¦¬ν•˜λ €κ³  ν•©λ‹ˆλ‹€.

μ œλ„ˆλ ˆμ΄ν„°

μ œλ„ˆλ ˆμ΄ν„° : μ΄ν„°λ ˆμ΄ν„°λ₯Ό μƒμ„±ν•΄μ£ΌλŠ” ν•¨μˆ˜μ΄λ©°, 파이썬의 μ‹œν€€μŠ€λ₯Ό μƒμ„±ν•˜λŠ” κ°μ²΄μž…λ‹ˆλ‹€.(μ œλ„ˆλ ˆμ΄ν„°λŠ” yield 문을 μ‚¬μš©ν•©λ‹ˆλ‹€)
μ΄ν„°λ ˆμ΄ν„° : λ°˜λ³΅λ¬Έμ„ ν™œμš©ν•΄μ„œ 데이터λ₯Ό μˆœνšŒν•˜λ©΄μ„œ μ²˜λ¦¬ν•˜λŠ” 것
(리슀트, λ”•μ…”λ„ˆλ¦¬, νŠœν”Œ λ“±)
μ‹œν€€μŠ€ : μ•žλ’€κ°€ κΌ­ μ§€μΌœμ Έμ•Ό ν•˜λŠ” μ‹œ/곡간적 μˆœμ„œ

1. μ œλ„ˆλ ˆμ΄ν„° μ—†λŠ” forλ¬Έ

def square_numbers(nums):
    result = []
    for i in nums:
        result.append(i * i)
    return result

my_nums = square_numbers([1, 2, 3, 4, 5])

print(my_nums)
>> [1, 4, 9, 16, 25]

printλ₯Ό 싀행해보면 μœ„μ˜ ν•¨μˆ˜κ°€ μ „λΆ€ μ‹€ν–‰λ˜μ–΄ 값이 λ°˜ν™˜λœ 것을 λ³Ό 수 μžˆμŠ΅λ‹ˆλ‹€.

2. μ œλ„ˆλ ˆμ΄ν„°λ₯Ό μ‚¬μš©ν•œ forλ¬Έ 

def square_numbers(nums):
    for i in nums:
        yield i * i

my_nums = square_numbers([1, 2, 3, 4, 5])  #1

print(my_nums)
>> <generator object gensquare_numbers at 0x7fc5fe928f90>

μœ„μ˜ λ‚΄μš©μ„ ν”„λ¦°νŠΈν•΄λ³΄λ©΄ 값이 λ‚˜μ˜€λŠ” 것이 μ•„λ‹Œ, μ œλ„ˆλ ˆμ΄ν„° μ˜€λΈŒμ νŠΈκ°€ 리턴이 λ©λ‹ˆλ‹€.
μžμ‹ μ΄ 리턴할 λͺ¨λ“  값을 λ©”λͺ¨λ¦¬μ— μ €μž₯ν•˜λŠ” 것이 μ•„λ‹Œ 호좜 될 λ•Œλ§ˆλ‹€ ν•˜λ‚˜μ”© 값을 μ „λ‹¬ν•˜κΈ° λ•Œλ¬Έμ— κΈ°λ‹€λ¦¬λŠ” μƒνƒœμž…λ‹ˆλ‹€.

def square_numbers(nums):
    for i in nums:
        yield i * i

my_nums = square_numbers([1, 2, 3, 4, 5])  #1

# κ·Έλƒ₯ ν”„λ¦°νŠΈκ°€ μ•„λ‹Œ next둜 κ°μ‹Έμ„œ ν”„λ¦°νŠΈ 해보면 1이 μ°ν˜€μ„œ λ‚˜μ˜΅λ‹ˆλ‹€.
print(next(my_nums))
>> 1
print(next(my_nums))
>> 4
print(next(my_nums))
>> 9
print(next(my_nums))
>> 16
print(next(my_nums))
>> 25

ν”„λ¦°νŠΈλ₯Ό 계속 λ°˜λ³΅ν•΄λ³΄λ©΄ 값이 λ‚˜μ˜€λŠ” 것을 μ•Œ 수 μžˆμŠ΅λ‹ˆλ‹€.
값이 μ „λΆ€ λ°˜ν™˜λœ μƒνƒœμ—μ„œ ν•œλ²ˆ 더 next λ₯Ό ν”„λ¦°νŠΈ ν•˜λ©΄,

print(next(my_nums))
>> Traceback (most recent call last):
  File "generator.py", line 22, in 
    print(next(my_nums))
StopIteration

StopIteration μ˜ˆμ™Έκ°€ λ°œμƒν•©λ‹ˆλ‹€.

μ œλ„ˆλ ˆμ΄ν„°λŠ” 일반적으둜 for문을 ν†΅ν•΄μ„œ ν˜ΈμΆœν•©λ‹ˆλ‹€.

def square_numbers(nums):
    for i in nums:
        yield i * i

my_nums = square_numbers([1, 2, 3, 4, 5])

for num in my_nums:
    print(num)

μœ„μ˜ μ½”λ“œλ₯Ό 싀행해보면 μ˜ˆμ™Έμ²˜λ¦¬κ°€ λ°œμƒν•˜μ§€ μ•Šκ³ , μ•Œμ•„μ„œ 멈μΆ₯λ‹ˆλ‹€.

λ°μ΄ν„°μ˜ 양이 λ§Žμ•„μ§€κ³  λ©”λͺ¨λ¦¬ μ‚¬μš©λŸ‰μ„ μ΅œμ ν™” ν•΄μ•Όν•˜λŠ” 상황이 μ˜¨λ‹€λ©΄ μ œλ„ˆλ ˆμ΄ν„°λ₯Ό μ‚¬μš©ν•΄μ•Όν•©λ‹ˆλ‹€.

yield λ₯Ό μ‚¬μš©ν•˜μ§€ μ•Šκ³ , μ œλ„ˆλ ˆμ΄ν„°λ₯Ό λ§Œλ“€ 수 μžˆμŠ΅λ‹ˆλ‹€.

result = (i*i for i in range(0,10))
for num in result:
    print(num)

리슀트 μ»΄ν”„λ¦¬ν—¨μ…˜ κ΅¬μ‘°μ—μ„œ κ΄„ν˜Έλ₯Ό '[]' κ°€ μ•„λ‹Œ '()' 둜 λ°”κΏ”μ£Όλ©΄ λ©λ‹ˆλ‹€.

좜처

profile
back-end 개발자

0개의 λŒ“κΈ€