티스토리 뷰

def sanitize(time_string):
    if '-' in time_string :
        splitter = '-'
    elif ':' in time_string :
        splitter = ':'
    else :
        return(time_string)

    (mins, secs) = time_string.split(splitter)

    return(mins + '.' + secs)

def get_coach_data(filename):
    try :
        with open(filename) as f:
            data = f.readline()
        return(data.strip().split(','))

    except IOError as ioerr:
        print('File error: ' + str(ioerr))
        return (None)



sarah = get_coach_data('sarah2.txt')
(sarah_name, sarah_dob) = sarah.pop(0), sarah.pop(0)
 
print(sarah_name + "'s fastest times are : "+ str(sorted(set([sanitize(t) for t in sarah]))[0:3]))

결과

Sarah Sweeney's fastest times are : ['2.18', '2.21', '2.22']

원본 데이터 살펴보기

Sarah Sweeney,2002-6-17,2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55,2:22,2-21,2.22
데이터 구조가 있음
  • 선수 이름
  • 생년월일
  • 시간 리스트

파이썬 딕셔너리 사용

딕셔너리는 데이터 값과 키를 연결한다.

유사어 : 매핑, 해시, 연관 배열

  • NameSarah Sweeney
  • Dob2002-6-17
  • Times[2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55,2:22,2-21,2.22]

딕셔너리를 사용한 리팩토링

def sanitize(time_string):
    if '-' in time_string :
        splitter = '-'
    elif ':' in time_string :
        splitter = ':'
    else :
        return(time_string)

    (mins, secs) = time_string.split(splitter)

    return(mins + '.' + secs)

"""
선수기록 정보 리턴
"""
def get_coach_data(filename):
    try :
        with open(filename) as f:
            data = f.readline()
            templ = data.strip().split(',') 
 
        return({'Name': templ.pop(0),
                'DOB' : templ.pop(0),
                'Times' : str(sorted(set([sanitize(t) for t in templ]))[0:3])
                })

    except IOError as ioerr:
        print('File error: ' + str(ioerr))
        return (None)


james = get_coach_data('james2.txt')
julie = get_coach_data('julie2.txt')
mikey = get_coach_data('mikey2.txt')
sarah = get_coach_data('sarah2.txt')
 
print(james['Name'] + "'s fastest times are : " + james['Times'])
print(julie['Name'] + "'s fastest times are : " + julie['Times'])
print(mikey['Name'] + "'s fastest times are : " + mikey['Times'])
print(sarah['Name'] + "'s fastest times are : " + sarah['Times'])

내장 리스트 상속 받기

"""
내장 리스트 상속 받기 
"""
class AthleteList(list) :
    def __init__(self, a_name, a_dob=None, a_times=[]):
        # 초기화 메서드
        list.__init__([])
        self.name = a_name
        self.dob = a_dob
        self.extend(a_times)

    def top3(self) :
        return(sorted(set([sanitize(t) for t in self]))[0:3])
 
 
def sanitize(time_string):
    if '-' in time_string :
        splitter = '-'
    elif ':' in time_string :
        splitter = ':'
    else :
        return(time_string)

    (mins, secs) = time_string.split(splitter)

    return(mins + '.' + secs)

"""
선수기록 정보 리턴
"""
def get_coach_data(filename):
    try :
        with open(filename) as f:
            data = f.readline()
            templ = data.strip().split(',') 
 
        return(AthleteList(templ.pop(0), templ.pop(0), templ))

    except IOError as ioerr:
        print('File error: ' + str(ioerr))
        return (None)

print('===내장 리스트 상속 받기===')
james = get_coach_data('james2.txt')
print(james.name + "'s fastest times are : " + str(james.top3()))

vera = AthleteList('Vera Vi')
vera.append('1.31')
print(vera.top3())
vera.extend(['2.22', "1-22", '2:22'])
print(vera.top3())

self

모든 메서드의 첫번째 인자로서, 언제나 객체 자신을 가리킵니다.

__init__()

초기화 메서드로서, 클래스 안에서 정의됩니다..

댓글