iterable objects คืออะไร?

ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

Kirill Smirnov

Data Science Consultant, Altran

นิยาม

iterable objects / Iterables - อ็อบเจกต์ใดก็ได้ที่ใช้ใน for loop ได้

  • list
  • tuple
  • set
  • dictionary
  • string
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

การวนซ้ำผ่าน list หรือ tuple

list:

droids = ['R2-D2', 'TC-16', 'C-3PO']

for droid in droids:
    print(droid)
R2-D2
TC-16
C-3PO

tuple:

droids = ('R2-D2', 'TC-16', 'C-3PO')

for droid in droids:
    print(droid)
R2-D2
TC-16
C-3PO
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

การวนซ้ำผ่าน set

battleships = {'X-Wing Fighter', 'Millennium Falcon', 'TIE Fighter'}

for battleship in battleships:
    print(battleship)
TIE Fighter
X-Wing Fighter
Millennium Falcon
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

การวนซ้ำผ่าน string

title = 'Star Wars'

for char in title:
    print(char)
S
t
a
r

W
a
r
s
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

การวนซ้ำผ่าน dictionary

episodes = {
    'Episode I': 'The Phantom Menace',
    'Episode II': 'Attack of the Clones',
    'Episode III': 'Revenge of the Sith', 
    'Episode IV': 'A New Hope',
    'Episode V': 'The Empire Strikes Back',
    'Episode VI': 'Return of the Jedi'
}
for episode in episodes:
    print(episode)
Episode I
Episode II
Episode III
Episode IV
Episode V
Episode VI
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

การดึงคู่ key-value

episodes = {
    'Episode I': 'The Phantom Menace',
    'Episode II': 'Attack of the Clones',
    'Episode III': 'Revenge of the Sith', 
    'Episode IV': 'A New Hope',
    'Episode V': 'The Empire Strikes Back',
    'Episode VI': 'Return of the Jedi'
}
for item in episodes.items():
    print(item)
('Episode I', 'The Phantom Menace')
('Episode II', 'Attack of the Clones')
('Episode III', 'Revenge of the Sith')
('Episode IV', 'A New Hope')
('Episode V', 'The Empire Strikes Back')
('Episode VI', 'Return of the Jedi')
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

การดึงคู่ key-value

episodes = {
    'Episode I': 'The Phantom Menace',
    'Episode II': 'Attack of the Clones',
    'Episode III': 'Revenge of the Sith', 
    'Episode IV': 'A New Hope',
    'Episode V': 'The Empire Strikes Back',
    'Episode VI': 'Return of the Jedi'
}
for title, subtitle in episodes.items():
    print(title + ': ' + subtitle)
'Episode I': 'The Phantom Menace'
'Episode II': 'Attack of the Clones'
'Episode III': 'Revenge of the Sith'
'Episode IV': 'A New Hope'
'Episode V': 'The Empire Strikes Back'
'Episode VI': 'Return of the Jedi'
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

อ็อบเจกต์ที่มองไม่เห็น: range

interval = range(0, 10)

print(interval)
range(0, 10)
for num in interval:
    print(num)
0
1
2
...
9
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

อ็อบเจกต์ที่มองไม่เห็น: enumerate

villains = ['Darth Maul', 'Palpatine', 'Darth Vader']
enum_villains = enumerate(villains)
for item in enum_villains:
    print(item)
(0, 'Darth Maul')
(1, 'Palpatine')
(2, 'Darth Vader')
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

อ็อบเจกต์ที่มองไม่เห็น: enumerate

villains = ['Darth Maul', 'Palpatine', 'Darth Vader']
enum_villains = enumerate(villains)
for idx, name in enum_villains:
    print(str(idx) + ' - ' + name)
0 - Darth Maul
1 - Palpatine
2 - Darth Vader
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

Iterables เป็น arguments

list(), tuple(), set(), etc.

villains = [
    'Darth Maul',
    'Palpatine',
    'Darth Vader'
]
list(enumerate(villains))
[
    (0, 'Darth Maul'),
    (1, 'Palpatine'),
    (2, 'Darth Vader')
]
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

Iterables เป็น arguments

list(), tuple(), set(), etc.

villains = [
    'Darth Maul',
    'Palpatine',
    'Darth Vader'
]
list(enumerate(villains))
[
    (0, 'Darth Maul'),
    ...
set(enumerate(villains))
{
    (0, 'Darth Maul'),
    (1, 'Palpatine'),
    (2, 'Darth Vader')
}
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

จะรู้ได้อย่างไรว่าเป็น Iterable

interval = range(0, 5)
interval_iter = iter(interval)
print(interval_iter)
<range_iterator object at 0x7f3bdf8ad300>

Iterator - อ็อบเจกต์ที่รู้วิธีดึงสมาชิกจาก Iterable ทีละตัวตามลำดับ

next(interval_iter)
0
next(interval_iter)
1
next(interval_iter)
2
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

StopIteration

next(interval_iter)
3
next(interval_iter)
4
next(interval_iter)
StopIteration
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

อธิบายการทำงานของ for loop

droids = ['R2-D2', 'TC-16', 'C-3PO']

for droid in droids:
    print(droid)
R2-D2
TC-16
C-3PO
iter_droids = iter(droids)

while True: try: except StopIteration: break
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

อธิบายการทำงานของ for loop

droids = ['R2-D2', 'TC-16', 'C-3PO']

for droid in droids:
    print(droid)
R2-D2
TC-16
C-3PO
iter_droids = iter(droids)

while True: try: droid = next(iter_droid) print(droid) except StopIteration: break
R2-D2
TC-16
C-3PO
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

Iterables หลายตัวเป็น Iterators ด้วย

  • iter()
  • next()

e.g. enumerate, finditer etc.

import re
pattern = re.compile(r'[\w\.]+@[a-z]+\.[a-z]+')

text = '[email protected] is the e-mail of John. He often writes to his boss '\
'at [email protected]. But the messages get forwarded to his secretary at [email protected].'

result = re.finditer(pattern, text)
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

iter() หรือ next()

iter()

result = re.finditer(pattern, text)

for item in result:
    print(item)
<_sre.SRE_Match object; span=(0, 22), match='[email protected]'>
<_sre.SRE_Match object; span=(77, 93), match='[email protected]'>
<_sre.SRE_Match object; span=(146, 162), match='[email protected]'>
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

iter() หรือ next()

next()

result = re.finditer(pattern, text)
next(result)
<_sre.SRE_Match object; span=(0, 22),
match='[email protected]'>
next(result)
<_sre.SRE_Match object; span=(77, 93),
match='[email protected]'>
next(result)
<_sre.SRE_Match object; span=(146, 162),
match='[email protected]'>
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

Iterables ที่ใช้ได้ครั้งเดียว

result = re.finditer(pattern, text)
for item in result:
    print(item)
<_sre.SRE_Match object; ...
<_sre.SRE_Match object; ...
<_sre.SRE_Match object; ...
for item in result:
    print(item)
# nothing
short_list = [2, 4]
for item in short_list:
    print(item)
2
4
for item in short_list:
    print(item)
2
4
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

การวนซ้ำผ่าน DataFrame

pars = {'weight': [168, 183, 198], 'height': [77, 79, 135]}
characters = pd.DataFrame(pars, index=['Luke Skywalker', 'Han Solo', 'Darth Vader'])
print(characters)
                weight  height
Luke Skywalker     168      77
Han Solo           183      79
Darth Vader        198     135
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

วิธีตรงไปตรงมา

for item in characters:
    print(item)
weight
height
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

.iterrows()

result = characters.iterrows()
print(result)
<generator object DataFrame.iterrows at 0x7f5dff6b9c50>
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

.iterrows()

result = characters.iterrows()
for item in result:
    print(item)

item $\rightarrow$ (index name, Series)

('Luke Skywalker',
weight    168
height     77
Name: Luke Skywalker, dtype: int64)
('Han Solo',
weight    183
height     79
Name: Han Solo, dtype: int64)
('Darth Vader',
weight    198
height    135
Name: Darth Vader, dtype: int64)
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

.iterrows()

result = characters.iterrows()
for index, series in result:
    print(index)
    print(series)
Luke Skywalker
weight    168
height     77
Name: Luke Skywalker, dtype: int64)
Han Solo
weight    183
height     79
Name: Han Solo, dtype: int64)
Darth Vader
weight    198
height    135
Name: Darth Vader, dtype: int64)
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

.iteritems()

result = characters.iteritems()
print(result)
<generator object DataFrame.iteritems at 0x7f5dff69f938>
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

.iteritems()

result = characters.iteritems()
for item in result:
    print(item)

item $\rightarrow$ (column name, Series)

('weight',
Luke Skywalker    168
Han Solo          183
Darth Vader       198
Name: weight, dtype: int64)
('height',
Luke Skywalker     77
Han Solo           79
Darth Vader       135
Name: height, dtype: int64)
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

.iteritems()

result = characters.iteritems()
for name, series in result:
    print(name)
    print(series)
weight
Luke Skywalker    168
Han Solo          183
Darth Vader       198
Name: weight, dtype: int64
height
Luke Skywalker     77
Han Solo           79
Darth Vader       135
Name: height, dtype: int64
ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

มาฝึกกันเถอะ!

ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

Preparing Video For Download...