ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • collections 모듈 - namedtuple
    개발 모음집/Python 2022. 5. 12. 15:56
    # 예제1. tuple() vs namedtuple()
    # tuple()
    a = ('John', 28, '남')
    b = ('Sally', 24, '여')
    
    for n in [a, b]:
    	print('%s은(는) %d 세의 %s성 입니다.' %n)
    
    '''
    결과
    John은(는) 28 세의 남성 입니다.
    Sally은(는) 24 세의 여성 입니다.
    '''
    
    import collections
    # namedtuple()
    Person = collections.namedtuple("Person", 'name age gender')
    P1 = Person(name='Jhon', age=28, gender='남')
    P2 = Person(name='Sally', age=28, gender='여')
    
    for n in [P1, P2]:
    	print('%s는(은) %d세의 %s성 입니다.' %n)
    '''
    결과
    Jhon는(은) 28세의 남성 입니다.
    Sally는(은) 28세의 여성 입니다.
    '''
    
    print(P1.name, P1.age, P1.gender)
    print(P2.name, P2.age, P2.gender)
    '''
    결과
    Jhon 28 남
    Sally 28 여
    '''
    

    2. collections.namedtuple()의 메소드들

    1) _make(iterable)

    • collections.namedtuple()의 _make() 함수는 기존에 생성된 namedtuple()에 새로운 인스턴스(객체)를 생성하는 메소드이다.
    # 예제2. collections.namedtuple()._make()
    import collections
    # Person 객체 만들기
    Person = collections.namedtuple("Person", 'name age gender')
    
    P1 = Person(name='Jhon', age=28, gender='남')
    P2 = Person(name='Sally', age=28, gender='여')
    # _make()를 이용하여 새로운 객체 생성
    P3 = Person._make(['Tom', 24, '남'])
    
    for n in [P1, P2, P3]:
    	print('%s는(은) %d세의 %s성 입니다.' %n)
    '''
    결과
    Jhon는(은) 28세의 남성 입니다.
    Sally는(은) 28세의 여성 입니다.
    Tom는(은) 24세의 남성 입니다.
    '''
    

    2) _asdict()

    • 기존에 생성된 namedtuple()의 인스턴스(객체)를 OrderedDict로 변환해 주는 함수이다.
    # 예제3. collections.namedtuple()._asdict()
    import collections
    # Person 객체 만들기
    
    Person = collections.namedtuple("Person", 'name age gender')
    P1 = Person(name='Jhon', age=28, gender='남')
    P2 = Person(name='Sally', age=28, gender='여')
    # _make()를 이용하여 새로운 객체 생성
    P3 = Person._make(['Tom', 24, '남'])
    
    # _asdict()를 이용하여 OrderedDict로 변환
    print(P3._asdict())
    '''
    결과
    OrderedDict([('name', 'Tom'), ('age', 24), ('gender', '남')])
    '''
    

    3) _replace(kwargs)

    기존에 생성된 namedtuple()의 인스턴스(객체)의 값을 변경할때 사용하는 함수이다.

    # 예제4. collections.namedtuple()._replace()
    import collections
    # Person 객체 만들기
    Person = collections.namedtuple("Person", 'name age gender')
    P1 = Person(name='Jhon', age=28, gender='남')
    P2 = Person(name='Sally', age=28, gender='여')
    P3 = Person._make(['Tom', 24, '남'])
    
    for n in [P1, P2, P3]:
    	print('%s는(은) %d세의 %s성 입니다.' %n)
    
    # _replace()를 이용하여 인스턴스 값 변경
    P1 = P1._replace(name='Neo')
    P2 = P2._replace(age=27)
    P3 = P3._replace(age=26)
    
    print('-'*20)
    for n in [P1, P2, P3]:
    	print('%s는(은) %d세의 %s성 입니다.' %n)
    '''
    결과
    Jhon는(은) 28세의 남성 입니다.
    Sally는(은) 28세의 여성 입니다.
    Tom는(은) 24세의 남성 입니다.
    --------------------
    Neo는(은) 28세의 남성 입니다.
    Sally는(은) 27세의 여성 입니다.
    Tom는(은) 26세의 남성 입니다.
    '''
    

    4) _fields

    • 생성된 namedtuple()의 필드명(field_names)를 tuple()형식으로 return해준다.
    # 예제5. collections.namedtuple()._fields
    import collections
    
    # Person 객체 만들기
    Person = collections.namedtuple("Person", 'name age gender')
    P1 = Person(name='Jhon', age=28, gender='남')
    P2 = Person(name='Sally', age=28, gender='여')
    P3 = Person._make(['Tom', 24, '남'])
    
    # _fields를 이용하여 필드명 출력
    print(P1._fields)
    '''
    결과
    ('name', 'age', 'gender')
    '''
    

    5) getattr()

    • ***getattr()는 collections.namedtuple()의 메소드는 아니지만, field_names로 namedtuple()의 인스턴스(객체)의 값을 추출해준다.***
    # 예제6. getattr()
    import collections
    # Person 객체 만들기
    Person = collections.namedtuple("Person", 'name age gender')
    P1 = Person(name='Jhon', age=28, gender='남')
    P2 = Person(name='Sally', age=28, gender='여')
    P3 = Person._make(['Tom', 24, '남'])
    print(getattr(P1, 'name'))
    print(getattr(P2, 'gender'))
    print(getattr(P3, 'age'))
    '''
    결과
    Jhon
    여
    24
    '''
    

    6) dictionary 에서 namedtuple()로 변환(*dict)

    • double-star-operator(**)는 딕셔너리(dict)를 namedtuple()로 변환해준다.
    # 예제7. double-star-operator (dict -> namedtuple)
    import collections
    # Person 객체 만들기
    Person = collections.namedtuple("Person", 'name age gender')
    P1 = Person(name='Jhon', age=28, gender='남')
    P2 = Person(name='Sally', age=28, gender='여')
    # double-star-operator
    dic = {'name' : 'Tom', 'age' : 24, 'gender' : '남'}
    P3 = Person(**dic)
    
    for n in [P1, P2, P3]:
    	# print('%s는(은) %d세의 %s성 입니다.' %n)
    	print(n)
    '''
    결과
    Person(name='Jhon', age=28, gender='남')
    Person(name='Sally', age=28, gender='여')
    Person(name='Tom', age=24, gender='남')
    '''
    

    '개발 모음집 > Python' 카테고리의 다른 글

    함수 주석  (0) 2022.05.17
    any, all 함수  (0) 2022.05.17
    operator의 itemgetter를 사용해서 리스트 정렬  (0) 2022.05.17
    collections 모듈 - OrderedDict  (0) 2022.05.12
    collections 모듈 - deque  (0) 2022.05.12
    collections 모듈 - defaultdict  (0) 2022.05.12
    collections 모듈 - Counter  (0) 2022.05.12
    vars() 내장함수  (0) 2022.05.10
Designed by Tistory.