logo

Python의 Namedtuple

Python은 ''라는 컨테이너 사전 유형을 지원합니다. 네임튜플() ' 모듈에 존재 ' 컬렉션 '. 이 기사에서는 NameTuple을 생성하는 방법과 NamedTuple에 대한 작업을 살펴보겠습니다.

Python에서 NamedTuple이란 무엇입니까?

~ 안에 파이썬 NamedTuple은 내부에 존재합니다. 컬렉션 모듈 . 이는 클래스와 유사하지만 전체 클래스를 정의하는 오버헤드 없이 간단하고 가벼운 데이터 구조를 생성하는 방법을 제공합니다. 사전과 마찬가지로 특정 값으로 해시된 키를 포함합니다. 반대로 키-값에서의 액세스와 반복 기능을 모두 지원합니다. 사전 부족.

Python NamedTuple 구문

명명된튜플(유형이름 필드_이름)

  • typename - 네임드튜플의 이름입니다.
  • field_names - 네임드튜플에 저장된 속성 목록입니다.

예: NamedTuple의 코드 구현은 다음과 같습니다. 파이썬 .

Python
# Python code to demonstrate namedtuple() from collections import namedtuple # Declaring namedtuple() Student = namedtuple('Student' ['name' 'age' 'DOB']) # Adding values S = Student('Nandini' '19' '2541997') # Access using index print('The Student age using index is : ' end='') print(S[1]) # Access using name print('The Student name using keyname is : ' end='') print(S.name) 

산출
The Student age using index is : 19 The Student name using keyname is : Nandini 

NamedTuple에 대한 작업

다음은 Namedtuple()을 사용하여 수행할 수 있는 작업입니다.

  • NameTuple 만들기
  • 액세스 작업
  • 변환 작업
  • 추가 작업

Python에서 NameTuple 만들기

그러면 명명된 Tuple() 함수를 사용하여 새로운 명명된 튜플 클래스가 생성됩니다. 컬렉션 기준 치수. 첫 번째 인수는 새 클래스의 이름이고 두 번째 인수는 필드 이름 목록입니다.

Python
from collections import namedtuple Point = namedtuple('Point' ['x' 'y']) p = Point(x=1 y=2) print(p.x p.y) 

산출
1 2 

액세스 작업

Python의 Namedtuple은 해당 필드에 액세스하는 편리한 방법을 제공합니다. 다음은 NamedTuple에 대해 Python에서 제공되는 일부 액세스 작업입니다.

  • 색인별 액세스
  • 키 이름으로 액세스
  • getattr()을 사용하여 액세스

색인별 액세스

Namedtuple()의 속성 값은 순서가 지정되어 있으며 인덱스로 접근할 수 없는 사전과 달리 인덱스 번호를 사용하여 접근할 수 있습니다. 이 예에서는 인덱스를 사용하여 학생의 데이터에 액세스합니다.

Python
# importing 'collections' for namedtuple() import collections # Declaring namedtuple() Student = collections.namedtuple('Student' ['name' 'age' 'DOB']) # Adding values S = Student('Nandini' '19' '2541997') # Access using index print('The Student age using index is : ' end='') print(S[1]) 

산출
The Student age using index is : 19 

키 이름으로 액세스

키 이름으로 접근하는 것도 사전처럼 허용됩니다. 이 예에서는 keyname을 사용하여 학생 이름에 액세스합니다.

Python
# importing 'collections' for namedtuple() import collections # Declaring namedtuple() Student = collections.namedtuple('Student' ['name' 'age' 'DOB']) # Adding values S = Student('Nandini' '19' '2541997') # Access using name print('The Student name using keyname is : ' end='') print(S.name) 

산출
The Student name using keyname is : Nandini 

getattr()을 사용하여 액세스

이는 네임드튜플과 키 값을 인수로 제공하여 값에 액세스하는 또 다른 방법입니다. 이 예에서 우리는 주어진 명명된 튜플에 있는 학생의 ID에 액세스하기 위해 getattr()을 사용하고 있습니다.

Python
# importing 'collections' for namedtuple() import collections # Declaring namedtuple() Student = collections.namedtuple('Student' ['name' 'age' 'DOB']) # Adding values S = Student('Nandini' '19' '2541997') # Access using getattr() print('The Student DOB using getattr() is : ' end='') print(getattr(S 'DOB')) 

산출
The Student DOB using getattr() is : 2541997 

변환 작업

Namedtuples는 다른 데이터 유형과 함께 작동하는 몇 가지 유용한 변환 작업을 제공합니다. 파이썬 . 다음은 Python에서 명명된 튜플에 대해 제공되는 다음 변환 작업입니다.

  • _make() 사용
  • _asdict() 사용하기
  • **(이중 별) 연산자 사용

_make()를 사용한 변환

이 함수는 다음을 반환하는 데 사용됩니다. iterable의 namestuple() 인수로 통과되었습니다. 이 예에서는 _make()를 사용하여 'li' 목록을 명명된 튜플로 변환합니다.

Python
# importing 'collections' for namedtuple() import collections # Declaring namedtuple() Student = collections.namedtuple('Student' ['name' 'age' 'DOB']) # Adding values S = Student('Nandini' '19' '2541997') # initializing iterable li = ['Manjeet' '19' '411997'] di = {'name': 'Nikhil' 'age': 19 'DOB': '1391997'} # using _make() to return namedtuple() print('The namedtuple instance using iterable is : ') print(Student._make(li)) 

산출
The namedtuple instance using iterable is : Student(name='Manjeet' age='19' DOB='411997') 

_asdict()를 사용한 변환 연산

이 함수는 다음을 반환합니다. 그만큼 주문사전() 명명된tuple()의 매핑된 값으로 구성됩니다. 이 예에서는 _asdict()를 사용하여 입력 목록을 명명된 튜플 인스턴스로 변환합니다.

Python
import collections # Declaring namedtuple() Student = collections.namedtuple('Student' ['name' 'age' 'DOB']) # Adding values S = Student('Nandini' '19' '2541997') # initializing iterable li = ['Manjeet' '19' '411997'] # initializing dict di = {'name': 'Nikhil' 'age': 19 'DOB': '1391997'} # using _asdict() to return an OrderedDict() print('The OrderedDict instance using namedtuple is : ') print(S._asdict()) 

산출
The OrderedDict instance using namedtuple is : OrderedDict([('name' 'Nandini') ('age' '19') ('DOB' '2541997')]) 

'**'(이중 별) 연산자 사용

이 함수는 사전을 명명된 Tuple()로 변환하는 데 사용됩니다. 이 예에서는 '**'를 사용하여 입력 목록을 명명된 튜플로 변환합니다.

Python
import collections # Declaring namedtuple() Student = collections.namedtuple('Student' ['name' 'age' 'DOB']) # Adding values S = Student('Nandini' '19' '2541997') # initializing iterable li = ['Manjeet' '19' '411997'] # initializing dict di = {'name': 'Nikhil' 'age': 19 'DOB': '1391997'} # using ** operator to return namedtuple from dictionary print('The namedtuple instance from dict is : ') print(Student(**di)) 

산출
The namedtuple instance from dict is : Student(name='Nikhil' age=19 DOB='1391997') 

추가 작업 

다음에서 제공되는 몇 가지 추가 작업이 있습니다. 파이썬 NamedTuples의 경우:

  • _전지
  • _바꾸다()
  • __새로운__()
  • __getnewargs__()

_전지

이 데이터 속성은 다음을 가져오는 데 사용됩니다. 모든 키 이름 선언된 네임스페이스의 이 예에서는 _fields를 사용하여 선언된 네임스페이스의 모든 키 이름을 가져옵니다.

Python
import collections Student = collections.namedtuple('Student' ['name' 'age' 'DOB']) # Adding values S = Student('Nandini' '19' '2541997') # using _fields to display all the keynames of namedtuple() print('All the fields of students are : ') print(S._fields) 

산출
All the fields of students are : ('name' 'age' 'DOB') 

_바꾸다()

_replace()는 str.replace()와 비슷하지만 필드라는 이름을 대상으로 합니다(원래 값을 수정하지 않습니다). 이 예에서는 _replace()를 사용하여 이름을 'Nandini'에서 'Manjeet'로 바꿉니다.

'prim'의 알고리즘'
Python
import collections # Declaring namedtuple() Student = collections.namedtuple('Student' ['name' 'age' 'DOB']) # Adding values S = Student('Nandini' '19' '2541997') # ._replace returns a new namedtuple  # it does not modify the original print('returns a new namedtuple : ') print(S._replace(name='Manjeet')) 

산출
returns a new namedtuple : Student(name='Manjeet' age='19' DOB='2541997') 

__새로운__()

이 함수는 명명된 튜플의 키에 할당하려는 값을 가져와 Student 클래스의 새 인스턴스를 반환합니다. 이 예에서는 __new__()를 사용하여 Student 클래스의 새 인스턴스를 반환합니다.

Python
import collections # Declaring namedtuple() Student = collections.namedtuple('Student' ['name' 'age' 'DOB']) # Adding values S = Student('Nandini' '19' '2541997') # Student.__new__ returns a new instance of Student(nameageDOB) print(Student.__new__(Student'Himesh''19''26082003')) 

산출
Student(name='Himesh' age='19' DOB='26082003') 

__getnewargs__()

이 함수는 명명된 튜플을 일반 튜플로 반환합니다. 이 예에서는 __getnewargs__()를 사용하여 동일한 작업을 수행합니다.

Python
import collections # Declaring namedtuple() Student = collections.namedtuple('Student' ['name' 'age' 'DOB']) # Adding values S = Student('Nandini' '19' '2541997') H=Student('Himesh''19''26082003') # .__getnewargs__ returns the named tuple as a plain tuple print(H.__getnewargs__()) 

산출
('Himesh' '19' '26082003') 
    1. 가변성 : 클래스의 인스턴스는 변경 가능하거나 불변일 수 있습니다.namedtuple인스턴스는 변경할 수 없습니다.
    2. 행동 양식 : 클래스는 메소드(함수)를 포함할 수 있지만namedtuple주로 명명된 필드를 사용하여 데이터를 저장하는 방법을 제공합니다.
    3. 계승 : 클래스는 복잡한 계층 구조를 생성할 수 있는 상속을 지원하지만namedtuple상속을 지원하지 않습니다.

    Typed dict와 Namedtuple의 차이점은 무엇입니까?

    1. 유형 확인 :TypedDict(에서typing모듈)은 유형 검사에 유용한 특정 키-값 쌍이 있는 사전에 대한 유형 힌트를 제공합니다.namedtuple유형 힌트를 제공하지 않습니다.
    2. 가변성 :TypedDict인스턴스는 변경 가능하여 값을 변경할 수 있습니다.namedtuple인스턴스는 변경할 수 없습니다.
    3. 구조 :TypedDict각 키에 대한 특정 유형의 사전 구조를 정의하는 데 사용됩니다.namedtuple튜플과 유사한 데이터에 대해 명명된 필드를 제공합니다.