๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ

[Python] Iterable, Iterator

category ๐Ÿ—ฏ๏ธLanguage/Python 2022. 6. 12. 22:02
728x90
 

 

 

Iterables

 

๊ธฐ๋ณธ ์„ค๋ช…

 

  • iterable ๋˜๋Š” interable container๋Š” ํ•œ ๋ฒˆ์— ํ•˜๋‚˜์”ฉ ๋ฉค๋ฒ„๋ฅผ ๋ฐ˜ํ™˜ํ•  ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  Python ๊ฐ์ฒด
  • for ๋ฌธ์—์„œ ๋ฐ˜๋ณต์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ด์ค๋‹ˆ๋‹ค.
    • for ๋ฌธ์—์„œ ํ™œ์šฉ๋  ๋•Œ, Python ๋‚ด๋ถ€์ ์œผ๋กœ๋Š” iter() ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ Iterator๋ผ๋Š” ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜์—ฌ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
    • Iterator๋Š” next() ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ ๋‹ค์Œ ๋ฉค๋ฒ„๋ฅผ ๋ฐ˜ํ™˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
studentList = ['Tom', 'Jack', 'Jane', 'Susan']
iteratorObject = iter(studentList)         # iterator ์ƒ์„ฑ

print(next(iteratorObject))   # 'Tom'
print(next(iteratorObject))   # 'Jack'
print(next(iteratorObject))   # 'Jane'
print(next(iteratorObject))   # 'Susan'
print(next(iteratorObject))   # 'StopItertation' ์˜ˆ์™ธ ๋ฐœ์ƒ

 

 

Iterable ๊ฐ์ฒด์ธ์ง€ ํ™•์ธํ•˜๊ธฐ

 

  • List, Dictionary, Set, String, Tuple, Bytes, Range๊ฐ€ ๋Œ€ํ‘œ์ ์ธ iterableํ•œ ํƒ€์ž…์ž…๋‹ˆ๋‹ค.
  • dir() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐ์ฒด์— __iter__ ๋ฉ”์†Œ๋“œ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.
stduentList = ['Tom', 'Jack', 'Jane', 'Susan']
dir(studentList)



'''
[ '__add__',
  '__class__',
  ...
  '__iter__'   # ์กด์žฌ
]

'''

 

 

Iterable ํ•œ ํด๋ž˜์Šค ๋งŒ๋“ค๊ธฐ

 

  • Python Programming์„ ํ•˜๋‹ค ๋ณด๋ฉด, ์‚ฌ์šฉ์ž ์ •์˜ ํด๋ž˜์Šค๋ฅผ ๋ฐ˜๋ณต๋ฌธ์—์„œ ๋ฐ˜๋ณตํ•˜๊ณ  ์‹ถ์€ ๋•Œ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.
  • ํ•ด๋‹น ํด๋ž˜์Šค์— __iter()__์™€ __next()__ ๋ฉ”์†Œ๋“œ๋ฅผ ๊ตฌํ˜„ํ•ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.
  • for ๋ฌธ์— ๋ฐ˜๋ณต ๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด, ํ•ด๋‹น ๋ฐ˜๋ณต ๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด์˜ __iter()__ ๋ฉ”์†Œ๋“œ๋ฅผ ํ†ตํ•ด iterator ๊ฐ์ฒด๋ฅผ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค.
    • ๊ทธ๋ฆฌ๊ณ  ๊ทธ iterator ๊ฐ์ฒด์˜ __next__() ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ๋ฃจํ”„๋ฅผ ๋Œ๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.
class MyClass:
    def __iter__(self):
    	...
        
    def __next__(self):
    	...

 

728x90
๋ฐ˜์‘ํ˜•