logo

Python의 NamedTuple

Python에서는 '특별한' 종류의 튜플을 'named tuple'이라고 합니다. Python 초보자는 특히 언제, 왜 구현해야 하는지에 대해 종종 당황합니다.

NamedTuple은 튜플이므로 튜플이 수행할 수 있는 모든 기능을 수행할 수 있습니다. 하지만 이는 단순한 Python 튜플 그 이상입니다. 다른 컴퓨터 언어에서는 C++와 마찬가지로 '클래스'와 훨씬 유사합니다. 이는 지정된 필드와 우리 사양에 따라 프로그래밍 방식으로 구축된 정의된 길이가 있는 튜플의 하위 유형입니다. 이 튜토리얼에서는 Python NamedTuples에 대해 설명하고 이를 사용하는 방법과 이를 활용해야 하는 시기와 이유를 보여줍니다.

파이썬 튜플이란 무엇입니까?

계속하기 전에 Python의 튜플을 다시 살펴봐야 한다고 생각합니다.

Python의 튜플은 많은 값을 저장할 수 있는 컨테이너입니다. 다음 경우를 고려하십시오.

암호

 numbers = (34, 32, 56, 24, 75, 24) 

보시다시피 괄호를 사용하여 정의합니다. 인덱스는 요소에 액세스하는 데 사용됩니다. (Python의 인덱싱은 0부터 시작한다는 점을 명심하세요.)

암호

 numbers[1] 

산출:

 32 

숫자[1] 파이썬 튜플은 해당 요소를 수정할 수 없다는 사실로 구분됩니다. 즉, 튜플의 요소는 변경할 수 없습니다.

Python NamedTuple 구문

먼저 다음과 같이 컬렉션이라는 Python 내장 모듈에서 NamedTuple을 가져와야 합니다.

 from collections import namedtuple 

다음은 NamedTuple을 구성하기 위한 기본 구문입니다.

 namedtuple(Name,[Names of Values]) 

이름 이는 NamedTuple에 제공하려는 제목의 매개변수입니다.

[값의 이름] 다양한 값이나 속성의 이름이 포함된 목록의 자리 표시자입니다.

Python NamedTuple 예

앞서 말한 것처럼 첫 번째 단계는 NamedTuple을 가져오는 것입니다.

 from collections import namedtuple 

이제 이전 부분의 구문을 사용하여 NamedTuple을 빌드할 수 있습니다.

 Student = namedtuple('Student',['Name','Class','Age','Subject','Marks']) 

이 예에서는

자바의 어떤 컬렉션

NamedTuple Student를 호출하고 목록에서 '이름', '클래스', '나이', '주제' 및 '마크' 값의 이름을 언급하기로 선택합니다. 그리고 우리는 첫 번째 NamedTuple - Student를 만들었습니다.

이제 다음과 같이 Student를 사용하여 필수 사양으로 Student1 집을 만들 수 있습니다.

안드로이드 프로세스 acore가 계속 중지됩니다.
 Studnet1 = Student('Itika', 11, 15, 'English', 79) 

[값 이름]의 레이블이나 필드가 취해야 하는 특정 값이나 콘텐츠만 필요합니다.

Student2라는 새 학생을 항목으로 만들려면 해당 값을 복사하여 새 변수의 필드에 붙여넣습니다.

 Studnet2 = Student('Arshia', 12, 17, 'Maths', 93) 

매번 필드의 레이블을 호출할 필요 없이 원하는 대로 신입생의 기록을 가져오기 위해 Student를 청사진으로 사용할 수 있음을 살펴보겠습니다.

점 표기법을 사용하여 NamedTuple의 값을 얻는 방법

점 메소드를 사용하여 NamedTuple 인스턴스 Student1 및 Student2의 값을 얻을 수 있습니다. 구문은 다음과 같습니다.

 . 

다음 코드 샘플은 이를 보여줍니다.

암호

 print (Student1.Age) print (Student1.Class) print (Student1.Subject) print (Student1.Marks) print (Student1.Name) 

산출:

 15 11 'English' 79 'Itika' 

마찬가지로 Student2.Age, Student2.Class 등을 사용하여 NamedTuple Student2와 관련된 변수를 검색할 수 있습니다.

NamedTuple의 액세스 방법

인덱스, 키워드 및 getattr() 함수를 사용하여 NamedTuple에서 값을 검색할 수 있습니다. NamedTuple의 필드 값은 엄격하게 정렬됩니다. 결과적으로 우리는 인덱스를 사용하여 이를 찾을 수 있습니다.

필드 이름은 NamedTuple에 의해 속성으로 변환됩니다. 결과적으로 getattr()을 사용하여 해당 필드에서 데이터를 검색할 수 있습니다.

암호

 import collections #create employee NamedTuple Participant = collections.namedtuple('Participant', ['Name', 'Age', 'Country']) #Adding two participants p1 = Participant('Itika', '21', 'India') p2 = Participant('Arshia', '19', 'Australia') #Accessing the items using index print( 'The name and country of the first participant are: ' + p1[0] + ' and ' + p1[2]) #Accessing the items using name of the field print( 'The name and country of the second participant are: ' + p2.Name + ' and ' + p2.Country) #Accessing the items using the method: getattr() print( 'The Age of participant 1 and 2 are: ' + getattr(p1, 'Age') + ' and ' + getattr(p2, 'Age')) 

산출:

 The name and country of the first participant are: Itika and India The name and country of the second participant are: Arshia and Australia The Age of participant 1 and 2 are: 21 and 19 

NamedTuple의 변환 절차

몇 가지 기술을 사용하여 다양한 컬렉션을 NamedTuple로 변환할 수 있습니다. _make() 함수를 사용하여 목록, 튜플 또는 기타 반복 가능한 객체를 NamedTuple 인스턴스로 변환할 수도 있습니다.

사전 데이터 형식 개체를 NamedTuple 컬렉션으로 변환할 수도 있습니다. 이 변환에는 ** 조작이 필요합니다.

OrderedDict 데이터 유형 항목인 NamedTuple은 해당 키를 사용하여 항목을 생성할 수 있습니다. _asdict() 함수를 호출하여 OrderedDict로 변환할 수 있습니다.

암호

 import collections #create employee NamedTuple Participant = collections.namedtuple('Participant', ['Name', 'Age', 'Country']) #List to Participants list_ = ['Itika', '21', 'India'] p1 = Participant._make(list_) print(p1) #Dict to convert Employee dict_ = {'Name':'Arshia', 'Age' : '19', 'Country' : 'Australia'} p2 = Participant(**dict_) print(p2) #Displaying the namedtuple as dictionary participant_dict = p1._asdict() print(participant_dict) 

산출:

 Participant(Name='Itika', Age='21', Country='India') Participant(Name='Arshia', Age='19', Country='Australia') {'Name': 'Itika', 'Age': '21', 'Country': 'India'} 

NamedTuple에 대한 추가 작업

_fields() 및 _replace와 같은 다른 메서드를 사용할 수 있습니다. _fields() 함수를 호출하여 NamedTuple이 어떤 필드를 가지고 있는지 확인할 수 있습니다. _replace() 함수는 한 값을 다른 값으로 바꾸는 데 사용됩니다.

암호

 import collections #create employee NamedTuple Participant = collections.namedtuple('Participant', ['Name', 'Age', 'Country']) #List to Participants p1 = Participant('Itika', '21', 'India') print(p1) print('The fields of Participant: ' + str(p1._fields)) #updating the country of participant p1 p1 = p1._replace(Country = 'Germany') print(p1) 

산출:

 Participant(Name='Itika', Age='21', Country='India') The fields of Participant: ('Name', 'Age', 'Country') Participant(Name='Itika', Age='21', Country='Germany') 

Python의 NamedTuple은 어떻게 작동합니까?

Python에서 NamedTuple을 사용하여 추가로 수행할 수 있는 작업이 무엇인지 살펴보겠습니다.

1. Python의 NamedTuple은 불변입니다.

Python의 NamedTuple은 일반 버전과 마찬가지로 수정할 수 없습니다. 우리는 그 특성을 변경할 수 없습니다.

이를 보여주기 위해 'Student'라는 이름의 튜플 특성 중 하나를 수정해 보겠습니다.

암호

 from collections import namedtuple Student = namedtuple('Student',['Name','Class','Age','Subject','Marks']) Student1 = Student('Arshia', 12, 17, 'Maths', 93) Student1.Class = 11 

산출:

 AttributeError Traceback (most recent call last) Input In [41], in () 2 Student = namedtuple('Student',['Name','Class','Age','Subject','Marks']) 3 Student1 = Student('Arshia', 12, 17, 'Maths', 93) ----> 4 Student1.Class = 11 AttributeError: can't set attribute 

보시다시피 AttributeError가 발생합니다. 결과적으로 NamedTuple은 불변이라고 추론할 수 있습니다.

2. Python NamedTuple에서 Python 사전 만들기

Python에서 NamedTuple은 사전과 유사하며 다음을 통해 하나로 변환할 수 있습니다.

영화 123 ~

암호

 from collections import namedtuple Student = namedtuple('Student',['Name','Class','Age','Subject','Marks']) Student1 = Student('Arshia', 12, 17, 'Maths', 93) print ( Student1._asdict() ) 

산출:

 {'Name': 'Arshia', 'Class': 12, 'Age': 17, 'Subject': 'Maths', 'Marks': 93} 

우리는 을 활용합니다. 이에 대한 asdict() 메서드입니다. 이는 또한 Python OrderedDict를 생성합니다.

3. 기본값이 있는 NamedTuple

네임드 튜플 클래스는 일반 클래스의 속성에 대한 초기 값을 설정할 수 있는 것과 동일한 방식으로 기본 매개변수를 사용하여 구성할 수 있습니다. 기본값이 있는 필드는 기본값이 없는 모든 필드 뒤에 나타나야 하므로 기본값은 가장 오른쪽 속성에 할당됩니다.

단 하나의 기본 항목으로 Student 클래스를 재정의해 보겠습니다.

암호

 from collections import namedtuple Student = namedtuple('Student', ['Name','Class','Age','Subject','Marks'], defaults = [100]) Student1 = Student('Arshia', 12, 17, 'Maths') print ( Student1 ) 

산출:

 Student(Name='Arshia', Class=12, Age=17, Subject='Maths', Marks=100) 

기본 숫자 100은 마크에 적용됩니다. 이는 하나의 값으로 NamedTuple을 생성하는 경우 선언의 가장 오른쪽 필드입니다.

필드를 Age로 명시적으로 지정하면 Age의 기본값이 적용됩니까?

Java에서 문자열을 정수로 변환

암호

 from collections import namedtuple Student = namedtuple('Student', ['Name','Class','Age','Subject','Marks'], defaults = [100]) Student1 = Student('Arshia', 12, 17, 'Maths') Student1 = Student(Age = 18) print ( Student1 ) 

산출:

 TypeError: Student.__new__() missing 3 required positional arguments: 'Name', 'Class', and 'Subject' 

내 대답은 아니오 야. NamedTuple에서는 필드 순서가 매우 엄격합니다. 명시적으로 선언하더라도 모호함과 잠재적인 어려움을 방지하기 위해 기본값은 가장 오른쪽에 있어야 합니다.

Python Namedtuple의 이점

물론 장점이 없다면 누구도 NamedTuple을 사용하지 않을 것입니다. 그래서 우리가 얻은 것은 다음과 같습니다:

1. 표준 튜플과 달리 Python의 NamedTuple은 제목으로 변수를 검색할 수 있습니다.

암호

 from collections import namedtuple Student = namedtuple('Student', ['Name','Class','Age','Subject','Marks'], defaults = [100]) Student1 = Student('Arshia', 12, 17, 'Maths') print ( Student1.Age ) 

산출:

 17 

2. 인스턴스별 사전을 포함하지 않기 때문에 Python NamedTuple은 기존 튜플과 마찬가지로 메모리 측면에서 효율적입니다. 그렇기 때문에 사전보다 빠릅니다.

결론

이 튜토리얼에서는 NamedTuples를 사용하여 튜플과 딕셔너리의 이점을 결합하는 방법, NamedTuples를 구축하는 방법 및 이를 사용하는 방법을 배웠습니다. Python에서 점 표기법을 사용하여 NamedTuples의 값을 검색하는 방법, 작동 방식

독자가 Python의 OOP에 대해 잘 알고 있다면 이것이 Python 클래스의 작동 방식과 동일하다는 것을 알게 될 것입니다. 클래스와 해당 속성은 각각 고유한 속성 값 집합을 갖는 더 많은 객체나 인스턴스를 생성하기 위한 청사진 역할을 합니다.

그러나 코드의 명확성을 높이기 위해 클래스를 정의하고 필수 특성을 제공하는 것은 일반적으로 과도하며 대신 NamedTuples를 생성하는 것이 훨씬 빠릅니다.