파이썬 특수 문법(데코레이터, 이터레이터등) - . 이터레이터 (iterator)

19. 이터레이터 (iterator)

  • 몇몇 특수한 데이터 집합은 내부의 각 데이터로 분리해서 처리할 수 있음
  • 예:
    • list, set, dictionary 등의 컬렉션(collection)
    • 문자열: 문자열을 이루는 각 문자 Sequence
  • 이와 같은 컬렉션(collection), Sequence등을 iterable 객체(iterable Object)라고 함
  • 간단히 for 구문으로 각 데이터를 탐색할 수 있는 데이터 집합
In [1]:
# 예1: 리스트 컬렉션
for num in [1, 2, 3, 4, 5]:
    print(num)
1
2
3
4
5
In [2]:
# 예2: 문자 Sequence
for char in "Dave Lee":
    print(char)
D
a
v
e
 
L
e
e

iterable 과 iterator

  • iterable 객체: itertator를 리턴할 수 있는 객체
    • 이터레이터를 리턴할 수 있는 객체
  • iterator
    • 순차적으로 다음 데이터를 리턴할 수 있는 객체
    • Iterator는 내장 함수 next 함수를 사용해서, 순환하는 다음 값을 반환함

내장 함수 iter()

  • iterator 객체를 생성할 수 있음
In [3]:
my_list = [1, 2, 3, 4, 5]
In [4]:
print(next(my_list))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-b578d09fe0eb> in <module>()
----> 1 print(next(my_list))

TypeError: 'list' object is not an iterator
In [5]:
my_list_iterator = iter(my_list)
In [6]:
print(next(my_list_iterator))
1


내장 함수 next()

  • Iterator의 다음 값, 즉 순환하는 값을 반환
In [7]:
iterator_my_list = iter(my_list)
In [11]:
next(iterator_my_list)
Out[11]:
4
In [18]:
next(iterator_my_list)
next(iterator_my_list)
next(iterator_my_list)
next(iterator_my_list)
Out[18]:
5
In [13]:
# 더이상 순회할 데이터가 없으면, StopIteration 발생
next(iterator_my_list)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-13-9435ceb6b26e> in <module>()
      1 # 더이상 순회할 데이터가 없으면, StopIteration 발생
----> 2 next(iterator_my_list)

StopIteration: 

for 구문과 iterator

  • for 구문 사용시, 파이썬은 매번 next 함수로 iterator의 다음 값을 읽어내는 것임
  • StopIteration 발생할 때까지 next 함수를 호출한다고 보면 됨

Custom 이터레이터 만들기

  • 직접 만들 수 있음
    • iterable 객체는 iter 메서드를 가지고 있는 클래스
    • iterator 객체는 next 메서드를 가지고 있는 클래스

iterable 객체와 iterator 클래스 만들기



In [14]:
class Counter:
    def __init__(self, stop):
        self.stop = stop    # 반복을 끝낼 숫자
 
    def __iter__(self):                      # <--- iterable 객체는 __iter__ 메서드가 존재함
        return Counter_Iterator(self.stop)   # <--- Counter 의 iterator 객체를 리턴해줌

class Counter_Iterator:
    def __init__(self, stop):
        self.current = 0    # 현재 상태를 확인하기 위한 속성
        self.stop = stop    

    def __next__(self):                 # <--- iterator는 __next__ 메서드가 존재함
        if self.current < self.stop:    # 현재 상태가 stop보다 적을 때는 현재 상태값을 리턴해주고, 1씩 상태값을 증가시킴
            return_value = self.current            
            self.current += 1           
            return return_value         
        else:                           # 현재 상태가 stop과 동일 또는 클 때는 StopIteration 이벤트를 발생시킴 
            raise StopIteration         # 예외 발생
In [15]:
counter_iterator = iter(Counter(5))
In [16]:
print (next(counter_iterator))
print (next(counter_iterator))
print (next(counter_iterator))
print (next(counter_iterator))
print (next(counter_iterator))
print (next(counter_iterator))
0
1
2
3
4
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-16-066bbda3f3fc> in <module>()
      4 print (next(counter_iterator))
      5 print (next(counter_iterator))
----> 6 print (next(counter_iterator))

<ipython-input-14-e947e7b9670f> in __next__(self)
     17             return return_value
     18         else:                           # 현재 상태가 stop과 동일 또는 클 때는 StopIteration 이벤트를 발생시킴
---> 19             raise StopIteration         # 예외 발생

StopIteration: 
In [17]:
for num in Counter(3):
    print (num)
0
1
2

iterable 객체이자 iterator로 한번에 클래스 만들기

In [162]:
class Counter:
    def __init__(self, stop):
        self.current = 0    # 현재 상태를 확인하기 위한 속성
        self.stop = stop    # 반복을 끝낼 숫자
 
    def __iter__(self):                      # <--- iterable 객체는 __iter__ 메서드가 존재함
        return self   # <--- Counter 의 iterator 객체를 리턴해줌

    def __next__(self):                 # <--- iterator는 __next__ 메서드가 존재함
        if self.current < self.stop:    # 현재 상태가 stop보다 적을 때는 현재 상태값을 리턴해주고, 1씩 상태값을 증가시킴
            return_value = self.current            
            self.current += 1           
            return return_value         
        else:                           # 현재 상태가 stop과 동일 또는 클 때는 StopIteration 이벤트를 발생시킴 
            raise StopIteration         # 예외 발생
In [18]:
counter_iterator = iter(Counter(5))
print (next(counter_iterator))
print (next(counter_iterator))
print (next(counter_iterator))
print (next(counter_iterator))
print (next(counter_iterator))
print (next(counter_iterator))
0
1
2
3
4
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-18-b454e2b4df33> in <module>()
      5 print (next(counter_iterator))
      6 print (next(counter_iterator))
----> 7 print (next(counter_iterator))

<ipython-input-14-e947e7b9670f> in __next__(self)
     17             return return_value
     18         else:                           # 현재 상태가 stop과 동일 또는 클 때는 StopIteration 이벤트를 발생시킴
---> 19             raise StopIteration         # 예외 발생

StopIteration: 
In [19]:
# iterable 객체이자 iterator임
print (next(Counter(2)))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-68b70cfc7dda> in <module>()
      1 # iterable 객체이자 iterator임
----> 2 print (next(Counter(2)))

TypeError: 'Counter' object is not an iterator


In [20]:
for num in Counter(3):
    print (num)
0
1
2
In [ ]:
def iter(object):
    return object.__iter__()

def next(object):
    return object.__next__()

for num in range(10):
    
In [21]:
class Counter:
    def __init__(self, stop):
        self.stop = stop    # 반복을 끝낼 숫자
 
    def __iter__(self):                      # <--- iterable 객체는 __iter__ 메서드가 존재함
        return Counter_Iterator(self.stop)   # <--- Counter 의 iterator 객체를 리턴해줌

class Counter_Iterator:
    def __init__(self, stop):
        self.current = stop    # 현재 상태를 확인하기 위한 속성
        self.stop = stop    

    def __next__(self):                 # <--- iterator는 __next__ 메서드가 존재함
        if self.current > 0:    # 현재 상태가 stop보다 적을 때는 현재 상태값을 리턴해주고, 1씩 상태값을 증가시킴
            return_value = self.current            
            self.current -= 1           
            return return_value         
        else:                           # 현재 상태가 stop과 동일 또는 클 때는 StopIteration 이벤트를 발생시킴 
            raise StopIteration         # 예외 발생
In [23]:
counter_iterator = iter(Counter(5))
print(next(counter_iterator))
print(next(counter_iterator))
print(next(counter_iterator))
print(next(counter_iterator))
print(next(counter_iterator))
5
4
3
2
1
초간단 연습1
- 위 Counter 클래스는 인자로 넣어지는 수까지를 0부터 순차적으로 1씩 증가된 값을 리턴해주는 클래스입니다.
- 이번에는 인자로 넣어지는 수부터 시작해서 0까지 순차적으로 1씩 감소된 값을 리턴해주는 클래스를 만들어보세요
In [17]:
class Counter:
    def __init__(self, stop):
        self.stop = stop    # 반복을 끝낼 숫자
 
    def __iter__(self):                      # <--- iterable 객체는 __iter__ 메서드가 존재함
        return Counter_Iterator(self.stop)   # <--- Counter 의 iterator 객체를 리턴해줌

class Counter_Iterator:
    def __init__(self, stop):
        self.current = stop    # 현재 상태를 확인하기 위한 속성

    def __next__(self):                 # <--- iterator는 __next__ 메서드가 존재함
        if self.current > 0:    # 현재 상태가 stop보다 적을 때는 현재 상태값을 리턴해주고, 1씩 상태값을 증가시킴
            return_value = self.current            
            self.current -= 1           
            return return_value         
        else:                           # 현재 상태가 stop과 동일 또는 클 때는 StopIteration 이벤트를 발생시킴 
            raise StopIteration         # 예외 발생

counter_iterator = iter(Counter(5))
print (next(counter_iterator))
print (next(counter_iterator))
5
4
협업 과제1(남에게 설명하면, 자신이 배운답니다.!)
- 특정 수와 배수를 입력받아 특정 수의 배수를 특정 수까지 리턴하는 이터레이터 만들기
예: 20, 2 를 입력받으면 0, 2, 4, ~~~ 20까지 리턴
In [20]:
class Counter:
    def __init__(self, stop, multiple):
        self.current = 0    # 현재 상태를 확인하기 위한 속성
        self.stop = stop    # 반복을 끝낼 숫자
        self.multiple = multiple
 
    def __iter__(self):                      # <--- iterable 객체는 __iter__ 메서드가 존재함
        return self   # <--- Counter 의 iterator 객체를 리턴해줌

    def __next__(self):                 # <--- iterator는 __next__ 메서드가 존재함
        if self.current < self.stop:    # 현재 상태가 stop보다 적을 때는 현재 상태값을 리턴해주고, 1씩 상태값을 증가시킴
            return_value = self.current            
            self.current = self.current + self.multiple           
            return return_value         
        else:                           # 현재 상태가 stop과 동일 또는 클 때는 StopIteration 이벤트를 발생시킴 
            raise StopIteration         # 예외 발생

counter_iterator = iter(Counter(20, 2))
print (next(counter_iterator))
print (next(counter_iterator))
print (next(counter_iterator))
print (next(counter_iterator))
print (next(counter_iterator))
print (next(counter_iterator))
0
2
4
6
8
10


협업 과제2(남에게 설명하면, 자신이 배운답니다.!)
다음 dataset은 이름을 가지고 있습니다. (타이타닉호 승선자 명단)
스트링에서 Mr. Miss, Mrs. 정보를 추출해서 각각 (Male), (Female) 출력해주는 데코레이터를 작성하세요
해당 데코레이터를 활용해서 이름 정보 리스트 변수를 넣어, 이름을 추력하는 함수를 작성해보세요
dataset과 이름에서 Mr. Miss. Mrs. 정보를 추출하는 코드는 다음 코드를 참고하세요

In [32]:
dataset = ['Braund, Mr. Owen Harris',
'Cumings, Mrs. John Bradley (Florence Briggs Thayer)',
'Heikkinen, Miss. Laina',
'Futrelle, Mrs. Jacques Heath (Lily May Peel)',
'Allen, Mr. William Henry',
'Moran, Mr. James',
'McCarthy, Mr. Timothy J',
'Palsson, Master. Gosta Leonard',
'Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)',
'Nasser, Mrs. Nicholas (Adele Achem)',
'Sandstrom, Miss. Marguerite Rut',
'Bonnell, Miss. Elizabeth',
'Saundercock, Mr. William Henry',
'Andersson, Mr. Anders Johan',
'Vestrom, Miss. Hulda Amanda Adolfina',
'Hewlett, Mrs. (Mary D Kingcome) ',
'Rice, Master. Eugene',
'Williams, Mr. Charles Eugene',
'Vander Planke, Mrs. Julius (Emelia Maria Vandemoortele)',
'Masselmani, Mrs. Fatima',
'Fynney, Mr. Joseph J',
'Beesley, Mr. Lawrence',
'McGowan, Miss. Anna "Annie"',
'Sloper, Mr. William Thompson',
'Palsson, Miss. Torborg Danira',
'Asplund, Mrs. Carl Oscar (Selma Augusta Emilia Johansson)',
'Emir, Mr. Farred Chehab',
'Fortune, Mr. Charles Alexander',
'Dwyer, Miss. Ellen "Nellie"',
'Todoroff, Mr. Lalio']
In [29]:
import re
p = re.compile('([A-Za-z]+)\.')
for name in dataset:
    matched = p.search(name)
    print(matched.group())
Mr.
Mrs.
Miss.
Mrs.
Mr.
Mr.
Mr.
Master.
Mrs.
Mrs.
Miss.
Miss.
Mr.
Mr.
Miss.
Mrs.
Master.
Mr.
Mrs.
Mrs.
Mr.
Mr.
Miss.
Mr.
Miss.
Mrs.
Mr.
Mr.
Miss.
Mr.

이름에서 앞에 이름만 빼고 싶은 분들이 있었음

In [34]:
import re
for name in dataset:
    names = name.split(' ')
    print (names[0])
Braund,
Cumings,
Heikkinen,
Futrelle,
Allen,
Moran,
McCarthy,
Palsson,
Johnson,
Nasser,
Sandstrom,
Bonnell,
Saundercock,
Andersson,
Vestrom,
Hewlett,
Rice,
Williams,
Vander
Masselmani,
Fynney,
Beesley,
McGowan,
Sloper,
Palsson,
Asplund,
Emir,
Fortune,
Dwyer,
Todoroff,
참고
다음 코드는 openpyxl 라이브러리로 엑셀파일에서 이름 데이터를 읽어내는 코드입니다.
실제로 대량의 데이터를 읽어내는 코드입니다.
간단한 문제: F 로 시작하는 이름만 2번째 열에 F 로 표시하기
In [24]:
import openpyxl
 
# 엑셀파일 열기
wb = openpyxl.load_workbook('data/name.xlsx')
 
# 현재 Active Sheet 얻기
ws = wb.active
# ws = wb.get_sheet_by_name("Sheet1")

for r in ws.rows:
    name = r[0].value
    if name[0] == 'F':
        ws.cell(row=r[0].row, column=2).value = 'F'
    # ws.cell(row=row_index, column=5).value = sum
 
    print(name)
 
# 엑셀 파일 저장
wb.save("score2.xlsx")
wb.close()
Kelly, Mr. James
Wilkes, Mrs. James (Ellen Needs)
Myles, Mr. Thomas Francis
Wirz, Mr. Albert
Hirvonen, Mrs. Alexander (Helga E Lindqvist)
Svensson, Mr. Johan Cervin
Connolly, Miss. Kate
Caldwell, Mr. Albert Francis
Abrahim, Mrs. Joseph (Sophie Halaut Easu)
Davies, Mr. John Samuel
Ilieff, Mr. Ylio
Jones, Mr. Charles Cresson
Snyder, Mrs. John Pillsbury (Nelle Stevenson)
Howard, Mr. Benjamin
Chaffee, Mrs. Herbert Fuller (Carrie Constance Toogood)
del Carlo, Mrs. Sebastiano (Argenia Genovesi)
Keane, Mr. Daniel
Assaf, Mr. Gerios
Ilmakangas, Miss. Ida Livija
Assaf Khalil, Mrs. Mariana (Miriam")"
Rothschild, Mr. Martin
Olsen, Master. Artur Karl
Flegenheim, Mrs. Alfred (Antoinette)
Williams, Mr. Richard Norris II
Ryerson, Mrs. Arthur Larned (Emily Maria Borie)
Robins, Mr. Alexander A
Ostby, Miss. Helene Ragnhild
Daher, Mr. Shedid
Brady, Mr. John Bertram
Samaan, Mr. Elias
Louch, Mr. Charles Alexander
Jefferys, Mr. Clifford Thomas
Dean, Mrs. Bertram (Eva Georgetta Light)
Johnston, Mrs. Andrew G (Elizabeth Lily" Watson)"
Mock, Mr. Philipp Edmund
Katavelas, Mr. Vassilios (Catavelas Vassilios")"
Roth, Miss. Sarah A
Cacic, Miss. Manda
Sap, Mr. Julius
Hee, Mr. Ling
Karun, Mr. Franz
Franklin, Mr. Thomas Parham
Goldsmith, Mr. Nathan
Corbett, Mrs. Walter H (Irene Colvin)
Kimball, Mrs. Edwin Nelson Jr (Gertrude Parsons)
Peltomaki, Mr. Nikolai Johannes
Chevre, Mr. Paul Romaine
Shaughnessy, Mr. Patrick
Bucknell, Mrs. William Robert (Emma Eliza Ward)
Coutts, Mrs. William (Winnie Minnie" Treanor)"
Smith, Mr. Lucien Philip
Pulbaum, Mr. Franz
Hocking, Miss. Ellen Nellie""
Fortune, Miss. Ethel Flora
Mangiavacchi, Mr. Serafino Emilio
Rice, Master. Albert
Cor, Mr. Bartol
Abelseth, Mr. Olaus Jorgensen
Davison, Mr. Thomas Henry
Chaudanson, Miss. Victorine
Dika, Mr. Mirko
McCrae, Mr. Arthur Gordon
Bjorklund, Mr. Ernst Herbert
Bradley, Miss. Bridget Delia
Ryerson, Master. John Borie
Corey, Mrs. Percy C (Mary Phyllis Elizabeth Miller)
Burns, Miss. Mary Delia
Moore, Mr. Clarence Bloomfield
Tucker, Mr. Gilbert Milligan Jr
Fortune, Mrs. Mark (Mary McDougald)
Mulvihill, Miss. Bertha E
Minkoff, Mr. Lazar
Nieminen, Miss. Manta Josefina
Ovies y Rodriguez, Mr. Servando
Geiger, Miss. Amalie
Keeping, Mr. Edwin
Miles, Mr. Frank
Cornell, Mrs. Robert Clifford (Malvina Helen Lamson)
Aldworth, Mr. Charles Augustus
Doyle, Miss. Elizabeth
Boulos, Master. Akar
Straus, Mr. Isidor
Case, Mr. Howard Brown
Demetri, Mr. Marinko
Lamb, Mr. John Joseph
Khalil, Mr. Betros
Barry, Miss. Julia
Badman, Miss. Emily Louisa
O'Donoghue, Ms. Bridget
Wells, Master. Ralph Lester
Dyker, Mrs. Adolf Fredrik (Anna Elisabeth Judith Andersson)
Pedersen, Mr. Olaf
Davidson, Mrs. Thornton (Orian Hays)
Guest, Mr. Robert
Birnbaum, Mr. Jakob
Tenglin, Mr. Gunnar Isidor
Cavendish, Mrs. Tyrell William (Julia Florence Siegel)
Makinen, Mr. Kalle Edvard
Braf, Miss. Elin Ester Maria
Nancarrow, Mr. William Henry
Stengel, Mrs. Charles Emil Henry (Annie May Morris)
Weisz, Mr. Leopold
Foley, Mr. William
Johansson Palmquist, Mr. Oskar Leander
Thomas, Mrs. Alexander (Thamine Thelma")"
Holthen, Mr. Johan Martin
Buckley, Mr. Daniel
Ryan, Mr. Edward
Willer, Mr. Aaron (Abi Weller")"
Swane, Mr. George
Stanton, Mr. Samuel Ward
Shine, Miss. Ellen Natalia
Evans, Miss. Edith Corse
Buckley, Miss. Katherine
Straus, Mrs. Isidor (Rosalie Ida Blun)
Chronopoulos, Mr. Demetrios
Thomas, Mr. John
Sandstrom, Miss. Beatrice Irene
Beattie, Mr. Thomson
Chapman, Mrs. John Henry (Sara Elizabeth Lawry)
Watt, Miss. Bertha J
Kiernan, Mr. John
Schabert, Mrs. Paul (Emma Mock)
Carver, Mr. Alfred John
Kennedy, Mr. John
Cribb, Miss. Laura Alice
Brobeck, Mr. Karl Rudolf
McCoy, Miss. Alicia
Bowenur, Mr. Solomon
Petersen, Mr. Marius
Spinner, Mr. Henry John
Gracie, Col. Archibald IV
Lefebre, Mrs. Frank (Frances)
Thomas, Mr. Charles P
Dintcheff, Mr. Valtcho
Carlsson, Mr. Carl Robert
Zakarian, Mr. Mapriededer
Schmidt, Mr. August
Drapkin, Miss. Jennie
Goodwin, Mr. Charles Frederick
Goodwin, Miss. Jessie Allis
Daniels, Miss. Sarah
Ryerson, Mr. Arthur Larned
Beauchamp, Mr. Henry James
Lindeberg-Lind, Mr. Erik Gustaf (Mr Edward Lingrey")"
Vander Planke, Mr. Julius
Hilliard, Mr. Herbert Henry
Davies, Mr. Evan
Crafton, Mr. John Bertram
Lahtinen, Rev. William
Earnshaw, Mrs. Boulton (Olive Potter)
Matinoff, Mr. Nicola
Storey, Mr. Thomas
Klasen, Mrs. (Hulda Kristina Eugenia Lofqvist)
Asplund, Master. Filip Oscar
Duquemin, Mr. Joseph
Bird, Miss. Ellen
Lundin, Miss. Olga Elida
Borebank, Mr. John James
Peacock, Mrs. Benjamin (Edith Nile)
Smyth, Miss. Julia
Touma, Master. Georges Youssef
Wright, Miss. Marion
Pearce, Mr. Ernest
Peruschitz, Rev. Joseph Maria
Kink-Heilmann, Mrs. Anton (Luise Heilmann)
Brandeis, Mr. Emil
Ford, Mr. Edward Watson
Cassebeer, Mrs. Henry Arthur Jr (Eleanor Genevieve Fosdick)
Hellstrom, Miss. Hilda Maria
Lithman, Mr. Simon
Zakarian, Mr. Ortin
Dyker, Mr. Adolf Fredrik
Torfa, Mr. Assad
Asplund, Mr. Carl Oscar Vilhelm Gustafsson
Brown, Miss. Edith Eileen
Sincock, Miss. Maude
Stengel, Mr. Charles Emil Henry
Becker, Mrs. Allen Oliver (Nellie E Baumgardner)
Compton, Mrs. Alexander Taylor (Mary Eliza Ingersoll)
McCrie, Mr. James Matthew
Compton, Mr. Alexander Taylor Jr
Marvin, Mrs. Daniel Warner (Mary Graham Carmichael Farquarson)
Lane, Mr. Patrick
Douglas, Mrs. Frederick Charles (Mary Helene Baxter)
Maybery, Mr. Frank Hubert
Phillips, Miss. Alice Frances Louisa
Davies, Mr. Joseph
Sage, Miss. Ada
Veal, Mr. James
Angle, Mr. William A
Salomon, Mr. Abraham L
van Billiard, Master. Walter John
Lingane, Mr. John
Drew, Master. Marshall Brines
Karlsson, Mr. Julius Konrad Eugen
Spedden, Master. Robert Douglas
Nilsson, Miss. Berta Olivia
Baimbrigge, Mr. Charles Robert
Rasmussen, Mrs. (Lena Jacobsen Solvang)
Murphy, Miss. Nora
Danbom, Master. Gilbert Sigvard Emanuel
Astor, Col. John Jacob
Quick, Miss. Winifred Vera
Andrew, Mr. Frank Thomas
Omont, Mr. Alfred Fernand
McGowan, Miss. Katherine
Collett, Mr. Sidney C Stuart
Rosenbaum, Miss. Edith Louise
Delalic, Mr. Redjo
Andersen, Mr. Albert Karvin
Finoli, Mr. Luigi
Deacon, Mr. Percy William
Howard, Mrs. Benjamin (Ellen Truelove Arman)
Andersson, Miss. Ida Augusta Margareta
Head, Mr. Christopher
Mahon, Miss. Bridget Delia
Wick, Mr. George Dennick
Widener, Mrs. George Dunton (Eleanor Elkins)
Thomson, Mr. Alexander Morrison
Duran y More, Miss. Florentina
Reynolds, Mr. Harold J
Cook, Mrs. (Selena Rogers)
Karlsson, Mr. Einar Gervasius
Candee, Mrs. Edward (Helen Churchill Hungerford)
Moubarek, Mrs. George (Omine Amenia" Alexander)"
Asplund, Mr. Johan Charles
McNeill, Miss. Bridget
Everett, Mr. Thomas James
Hocking, Mr. Samuel James Metcalfe
Sweet, Mr. George Frederick
Willard, Miss. Constance
Wiklund, Mr. Karl Johan
Linehan, Mr. Michael
Cumings, Mr. John Bradley
Vendel, Mr. Olof Edvin
Warren, Mr. Frank Manley
Baccos, Mr. Raffull
Hiltunen, Miss. Marta
Douglas, Mrs. Walter Donald (Mahala Dutton)
Lindstrom, Mrs. Carl Johan (Sigrid Posse)
Christy, Mrs. (Alice Frances)
Spedden, Mr. Frederic Oakley
Hyman, Mr. Abraham
Johnston, Master. William Arthur Willie""
Kenyon, Mr. Frederick R
Karnes, Mrs. J Frank (Claire Bennett)
Drew, Mr. James Vivian
Hold, Mrs. Stephen (Annie Margaret Hill)
Khalil, Mrs. Betros (Zahie Maria" Elias)"
West, Miss. Barbara J
Abrahamsson, Mr. Abraham August Johannes
Clark, Mr. Walter Miller
Salander, Mr. Karl Johan
Wenzel, Mr. Linhart
MacKay, Mr. George William
Mahon, Mr. John
Niklasson, Mr. Samuel
Bentham, Miss. Lilian W
Midtsjo, Mr. Karl Albert
de Messemaeker, Mr. Guillaume Joseph
Nilsson, Mr. August Ferdinand
Wells, Mrs. Arthur Henry (Addie" Dart Trevaskis)"
Klasen, Miss. Gertrud Emilia
Portaluppi, Mr. Emilio Ilario Giuseppe
Lyntakoff, Mr. Stanko
Chisholm, Mr. Roderick Robert Crispin
Warren, Mr. Charles William
Howard, Miss. May Elizabeth
Pokrnic, Mr. Mate
McCaffry, Mr. Thomas Francis
Fox, Mr. Patrick
Clark, Mrs. Walter Miller (Virginia McDowell)
Lennon, Miss. Mary
Saade, Mr. Jean Nassr
Bryhl, Miss. Dagmar Jenny Ingeborg 
Parker, Mr. Clifford Richard
Faunthorpe, Mr. Harry
Ware, Mr. John James
Oxenham, Mr. Percy Thomas
Oreskovic, Miss. Jelka
Peacock, Master. Alfred Edward
Fleming, Miss. Honora
Touma, Miss. Maria Youssef
Rosblom, Miss. Salli Helena
Dennis, Mr. William
Franklin, Mr. Charles (Charles Fardon)
Snyder, Mr. John Pillsbury
Mardirosian, Mr. Sarkis
Ford, Mr. Arthur
Rheims, Mr. George Alexander Lucien
Daly, Miss. Margaret Marcella Maggie""
Nasr, Mr. Mustafa
Dodge, Dr. Washington
Wittevrongel, Mr. Camille
Angheloff, Mr. Minko
Laroche, Miss. Louise
Samaan, Mr. Hanna
Loring, Mr. Joseph Holland
Johansson, Mr. Nils
Olsson, Mr. Oscar Wilhelm
Malachard, Mr. Noel
Phillips, Mr. Escott Robert
Pokrnic, Mr. Tome
McCarthy, Miss. Catherine Katie""
Crosby, Mrs. Edward Gifford (Catherine Elizabeth Halstead)
Allison, Mr. Hudson Joshua Creighton
Aks, Master. Philip Frank
Hays, Mr. Charles Melville
Hansen, Mrs. Claus Peter (Jennie L Howard)
Cacic, Mr. Jego Grga
Vartanian, Mr. David
Sadowitz, Mr. Harry
Carr, Miss. Jeannie
White, Mrs. John Stuart (Ella Holmes)
Hagardon, Miss. Kate
Spencer, Mr. William Augustus
Rogers, Mr. Reginald Harry
Jonsson, Mr. Nils Hilding
Jefferys, Mr. Ernest Wilfred
Andersson, Mr. Johan Samuel
Krekorian, Mr. Neshan
Nesson, Mr. Israel
Rowe, Mr. Alfred G
Kreuchen, Miss. Emilie
Assam, Mr. Ali
Becker, Miss. Ruth Elizabeth
Rosenshine, Mr. George (Mr George Thorne")"
Clarke, Mr. Charles Valentine
Enander, Mr. Ingvar
Davies, Mrs. John Morgan (Elizabeth Agnes Mary White) 
Dulles, Mr. William Crothers
Thomas, Mr. Tannous
Nakid, Mrs. Said (Waika Mary" Mowad)"
Cor, Mr. Ivan
Maguire, Mr. John Edward
de Brito, Mr. Jose Joaquim
Elias, Mr. Joseph
Denbury, Mr. Herbert
Betros, Master. Seman
Fillbrook, Mr. Joseph Charles
Lundstrom, Mr. Thure Edvin
Sage, Mr. John George
Cardeza, Mrs. James Warburton Martinez (Charlotte Wardle Drake)
van Billiard, Master. James William
Abelseth, Miss. Karen Marie
Botsford, Mr. William Hull
Whabee, Mrs. George Joseph (Shawneene Abi-Saab)
Giles, Mr. Ralph
Walcroft, Miss. Nellie
Greenfield, Mrs. Leo David (Blanche Strouse)
Stokes, Mr. Philip Joseph
Dibden, Mr. William
Herman, Mr. Samuel
Dean, Miss. Elizabeth Gladys Millvina""
Julian, Mr. Henry Forbes
Brown, Mrs. John Murray (Caroline Lane Lamson)
Lockyer, Mr. Edward
O'Keefe, Mr. Patrick
Lindell, Mrs. Edvard Bengtsson (Elin Gerda Persson)
Sage, Master. William Henry
Mallet, Mrs. Albert (Antoinette Magnin)
Ware, Mrs. John James (Florence Louise Long)
Strilic, Mr. Ivan
Harder, Mrs. George Achilles (Dorothy Annan)
Sage, Mrs. John (Annie Bullen)
Caram, Mr. Joseph
Riihivouri, Miss. Susanna Juhantytar Sanni""
Gibson, Mrs. Leonard (Pauline C Boeson)
Pallas y Castello, Mr. Emilio
Giles, Mr. Edgar
Wilson, Miss. Helen Alice
Ismay, Mr. Joseph Bruce
Harbeck, Mr. William H
Dodge, Mrs. Washington (Ruth Vidaver)
Bowen, Miss. Grace Scott
Kink, Miss. Maria
Cotterill, Mr. Henry Harry""
Hipkins, Mr. William Edward
Asplund, Master. Carl Edgar
O'Connor, Mr. Patrick
Foley, Mr. Joseph
Risien, Mrs. Samuel (Emma)
McNamee, Mrs. Neal (Eileen O'Leary)
Wheeler, Mr. Edwin Frederick""
Herman, Miss. Kate
Aronsson, Mr. Ernst Axel Algot
Ashby, Mr. John
Canavan, Mr. Patrick
Palsson, Master. Paul Folke
Payne, Mr. Vivian Ponsonby
Lines, Mrs. Ernest H (Elizabeth Lindsey James)
Abbott, Master. Eugene Joseph
Gilbert, Mr. William
Kink-Heilmann, Mr. Anton
Smith, Mrs. Lucien Philip (Mary Eloise Hughes)
Colbert, Mr. Patrick
Frolicher-Stehli, Mrs. Maxmillian (Margaretha Emerentia Stehli)
Larsson-Rondberg, Mr. Edvard A
Conlon, Mr. Thomas Henry
Bonnell, Miss. Caroline
Gale, Mr. Harry
Gibson, Miss. Dorothy Winifred
Carrau, Mr. Jose Pedro
Frauenthal, Mr. Isaac Gerald
Nourney, Mr. Alfred (Baron von Drachstedt")"
Ware, Mr. William Jeffery
Widener, Mr. George Dunton
Riordan, Miss. Johanna Hannah""
Peacock, Miss. Treasteall
Naughton, Miss. Hannah
Minahan, Mrs. William Edward (Lillian E Thorpe)
Henriksson, Miss. Jenny Lovisa
Spector, Mr. Woolf
Oliva y Ocana, Dona. Fermina
Saether, Mr. Simon Sivertsen
Ware, Mr. Frederick
Peter, Master. Michael J

협업과제2를 실제 엑셀파일까지 연계해서 풀어보기



In [30]:
import openpyxl
import re
# 엑셀파일 열기
wb = openpyxl.load_workbook('data/name.xlsx')
 
# 현재 Active Sheet 얻기
ws = wb.active
# ws = wb.get_sheet_by_name("Sheet1")

for r in ws.rows:
    name = r[0].value
    p = re.compile('([A-Za-z]+)\.')
    if p.search(name):
        matched = p.search(name)
        if matched.group() == 'Mr.' or matched.group() == 'Master.':
            ws.cell(row=r[0].row, column=2).value = '(Male)'
        elif matched.group() == 'Mrs.' or matched.group() == 'Miss.' or matched.group() == 'Ms.':
            ws.cell(row=r[0].row, column=2).value = '(Female)'
        else:
            ws.cell(row=r[0].row, column=2).value = '(Unknown)'
 
# 엑셀 파일 저장
wb.save("score2.xlsx")
wb.close()