파이썬[Python]: collections - namedtuple 클래스

collections 모듈 - namedtuple 클래스(class)


/// 설명

typename이름으로 되어진 새로운 튜플의 subclass를 반환합니다. 이 subclass는 튜플 객체를 생성하는데 사용되어 집니다.(속성(attribute)과 색인(index)으로 접근 가능합니다.)
rename 인자는 fieldname에 유효하지 않은 값이 들어오면 자동으로 변환하여줍니다.
default 인자는 fieldname에 값을 전달하여 줍니다.(오른쪽 파라미터부터 접근합니다.)
module 인자는 생성된 튜플의 __module__ 속성을 이 값으로 만들어 줍니다.

※ 형식
class collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)

/// 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import collections
 
# Test = collections.namedtuple('Test', 'a b c')
# Test = collections.namedtuple('Test', 'a, b, c')
Test = collections.namedtuple('Test', ['a''b''c'])
 
print(type(Test))  # <class 'type'>
print(Test)  # <class '__main__.Test'>
 
test_nt = Test(a=1, b=2, c=3)
print(test_nt)  # Test(a=1, b=2, c=3)
print(test_nt[0], test_nt[1], test_nt[2])  # 1 2 3
print(test_nt.a, test_nt.b, test_nt.c)  # 1 2 3
 
print(type(test_nt))  # <class '__main__.Test'>
 
# unpack like a regular tuple
a, b, c = test_nt
print(a, b, c)  # 1 2 3
 
# unpacking tuple
test_tuple = (456)
x, y, z = test_tuple
print(x, y, z)  # 4 5 6
 
cs

* 실행환경: Microsoft Windows 10 Homes
* 인터프리터: 파이썬(Python 3.9)


– 당신을 응원합니다. –

댓글

이 블로그의 인기 게시물

파이썬[Python]: 내장함수 - from_bytes 메서드

파이썬[Python]: 내장함수 - __len__ 메서드

파이썬[Python]: kivy - 한글 사용

파이썬[Python]: 내장함수 - bit_length 메서드

C 언어: sin 함수, cos 함수, tan 함수