logo

Python の NamedTuple

Python では、「特別な」種類のタプルは「名前付きタプル」と呼ばれます。 Python の初心者は、特にいつ、なぜそれを実装する必要があるのか​​、よく困惑します。

NamedTuple はタプルであるため、タプルが実行できるすべての機能を実行できます。ただし、これは単純な Python タプル以上のものです。他のコンピューター言語では、C++ と同様に、「クラス」によく似ています。これは、指定されたフィールドと、仕様に従ってプログラムで構築された定義された長さを持つタプルのサブタイプです。このチュートリアルでは、Python NamedTuples について説明し、その使用方法と、いつ、そしてなぜ使用する必要があるかを示します。

Python タプルとは何ですか?

次に進む前に、Python のタプルを再検討する必要があると考えています。

Python のタプルは、多くの値を格納できるコンテナです。次の場合を考えてみましょう。

コード

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

ご覧のとおり、括弧を使用して定義します。インデックスは要素にアクセスするために使用されます。 (Python でのインデックス付けは 0 から始まることに注意してください。)

コード

 numbers[1] 

出力:

 32 

Numbers[1] Python タプルは、その要素を変更できないという事実によって分離されています。つまり、タプルの要素は不変です。

Python の名前付きタプルの構文

次に示すように、最初にコレクションと呼ばれる Python の組み込みモジュールから NamedTuple をインポートする必要があります。

 from collections import namedtuple 

以下は、NamedTuple を構築するための基本的な構文です。

 namedtuple(Name,[Names of Values]) 

名前 これは、NamedTuple に付けたいタイトルのパラメータであり、

[値の名前] は、さまざまな値または属性の名前を含むリストのプレースホルダーです。

Python の名前付きタプルの例

前述したように、最初のステップは NamedTuple をインポートすることです。

 from collections import namedtuple 

これで、前の部分の構文を使用して NamedTuple を構築できるようになります。

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

この例では、

npm クリーンキャッシュ強制

NamedTuple Student を呼び出し、リスト内の値の名前、'Name'、'Class'、'Age'、'Subject'、および 'Marks' を言及することにします。そして、最初の NamedTuple - Student を作成しました。

ここで、次のように Student を使用して、必要な仕様を持つ家 Student1 を作成できます。

Javaはすべてを置き換えます
 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」という名前のタプルの特性の 1 つを変更してみます。

コード

 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 は不変であると推測できます。

CSSの最初の子

2. Python NamedTuple から Python 辞書を作成する

Python では、NamedTuple は辞書に似ており、次のように変換できます。

コード

 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

名前付きタプル クラスは、通常のクラスで属性の初期値を設定するのと同じ方法で、デフォルト パラメーターを使用して構成できます。デフォルト値を持つフィールドは、デフォルト値のないすべてのフィールドの後に表示される必要があるため、デフォルト値は右端の属性に割り当てられます。

デフォルトのエントリを 1 つだけ使用して Student クラスを再定義してみましょう。

コード

Javaのランダム値ジェネレーター
 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 がマークに適用されます。マークは、値を 1 つだけ指定して NamedTuple を作成する場合、宣言の右端のフィールドになります。

フィールドを年齢として明示的に指定した場合、年齢のデフォルト値が適用されますか?

コード

 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 を使用する人はいません。というわけで、以下のとおりです。

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 を構築する方がはるかに高速です。