๐Ÿ“—
JunegLee's TIL
  • TIL
  • python
    • class
    • String Basic
    • regularExpression
    • String function
    • Generator
    • String format
    • getset
    • module
    • while
    • numpy
    • print()
    • matplotlib
    • for
    • Boolean
    • tuple
    • package
    • input(variable)
    • list
    • if
    • file
    • type()
    • pandas
    • function
    • dictionary
    • ๊ตฌ๋ฌธ ์˜ค๋ฅ˜์™€ ์˜ˆ์™ธ
    • builtinFunction
    • Constructor
  • algorithm
    • sort
      • mergeSort
      • insertionSort
      • bubbleSort
      • heapSort
      • quickSort
      • selectionSort
    • recursion
    • Greedy
    • DepthFirstSearch
    • basic
      • DataStructure
    • hash
    • BreadthFirstSearch
  • tensorflow
    • keras
      • layers
        • Flatten
        • Flatten
        • Dense
        • Dense
        • Conv2D
        • Conv2D
    • tensorflow1x
    • tensorflow2x
  • DB
    • setting
    • join
    • subQuery
    • overview
  • deep-learning
    • neuralNetwork
    • perceptron
    • neuralNetworkLearning
    • convolution neural network
    • Gradient Descent
    • Linear Regression
    • backPropagation
    • logistic regression
    • overview
  • textPreprocessing
    • overview
  • java
    • basics
      • generic
      • Variable
      • String
    • theory
      • Object Oriented Programing
  • NLP
    • Embedding
    • Natural Language Processing
Powered by GitBook
On this page

Was this helpful?

  1. python

Generator

์ œ๋„ˆ๋ ˆ์ดํ„ฐ Generator

  • ์ดํ„ฐ๋ ˆ์ดํ„ฐ๋ฅผ ์ง์ ‘ ๋งŒ๋“ค ๋•Œ ์‚ฌ์šฉํ•˜๋Š” ์ฝ”๋“œ๋กœ์จ, ํ•จ์ˆ˜ ๋‚ด๋ถ€์— yield ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ํ•ด๋‹น ํ•จ์ˆ˜๋Š” ์ œ๋„ˆ๋ ˆ์ดํ„ฐ ํ•จ์ˆ˜๊ฐ€ ๋˜๋ฉฐ,

  • ์ผ๋ฐ˜ ํ•จ์ˆ˜์™€ ๋‹ฌ๋ฆฌ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•ด๋„ ํ•จ์ˆ˜ ๋‚ด๋ถ€์˜ ์ฝ”๋“œ๊ฐ€ ์‹คํ–‰๋˜์ง€ ์•Š๋Š”๋‹ค

  • ์ œ๋„ˆ๋ ˆ์ดํ„ฐ ๊ฐ์ฒด๋Š” next() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด ํ•จ์ˆ˜ ๋‚ด๋ถ€์˜ ์ฝ”๋“œ๋ฅผ ์‹คํ–‰ํ•˜์—ฌ์•ผ ํ•œ๋‹ค

    def test():
      print("ํ•จ์ˆ˜๊ฐ€ ํ˜ธ์ถœ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")
      yield test
    print("A ์ง€์  ํ†ต๊ณผ")
    test()
    print("B ์ง€์  ํ†ต๊ณผ")
    test()
    print(test())
    # A ์ง€์  ํ†ต๊ณผ
    # B ์ง€์  ํ†ต๊ณผ
    # <generator object test at 0x000001981619B9C8>

    ์ œ๋„ˆ๋ ˆ์ดํ„ฐ ๊ฐ์ฒด์™€ next() ํ•จ์ˆ˜

  • next() ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•œ ์ดํ›„ yield ํ‚ค์›Œ๋“œ๋ฅผ ๋งŒ๋‚˜์ง€ ๋ชปํ•˜๊ณ  ํ•จ์ˆ˜๊ฐ€ ๋๋‚˜๋ฉด

  • StopIteration์ด๋ผ๋Š” ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค

def test():
    print("A ์ง€์  ํ†ต๊ณผ")
    yield 1
    print("B ์ง€์  ํ†ต๊ณผ")
    yield 2
    print("C ์ง€์  ํ†ต๊ณผ")
output = test()

print("D ์ง€์  ํ†ต๊ณผ")
a = next(output)
print(a)

print("E ์ง€์  ํ†ต๊ณผ")
b = next(output)
print(b)

print("F ์ง€์  ํ†ต๊ณผ")
c = next(output)
print(c)

next(output)
# D ์ง€์  ํ†ต๊ณผ
# A ์ง€์  ํ†ต๊ณผ
# 1
# E ์ง€์  ํ†ต๊ณผ
# B ์ง€์  ํ†ต๊ณผ
# 2
# F ์ง€์  ํ†ต๊ณผ
# C ์ง€์  ํ†ต๊ณผ
# => error ๋ฐœ์ƒ
Traceback (most recent call last):
  File "test.py", line 18, in <module>
    c = next(output)
StopIteration
PreviousString functionNextString format

Last updated 4 years ago

Was this helpful?