logo

Python の名前付きタプル

Python は、と呼ばれるタイプのコンテナ辞書をサポートしています。 名前付きタプル() モジュール内に存在する コレクション 。この記事では、NameTuple の作成方法と NamedTuple での操作について説明します。

Python の NamedTuple とは何ですか?

パイソン , NamedTuple は内部に存在します。 コレクションモジュール 。これは、クラスに似たシンプルで軽量のデータ構造を作成する方法を提供しますが、完全なクラスを定義するオーバーヘッドはありません。辞書と同様に、これらには特定の値にハッシュされたキーが含まれています。それどころか、キーと値からのアクセスと反復の両方をサポートしています。 辞書 足らない。

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

名前付きタプル(タイプ名, フィールド名)



  • typename – 名前付きタプルの名前。
  • field_names – 名前付きタプルに保存されている属性のリスト。

例: NamedTuple のコード実装を以下に示します。 パイソン

npm クリーンキャッシュ強制
Python3
# 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() を使用して実行できる操作です。

  • 名前タプルを作成する
  • アクセス操作
  • 変換操作
  • 追加の操作

Python で NameTuple を作成する

これにより、namedtuple() 関数を使用して新しい namestuple クラスが作成されます。 コレクション モジュール。最初の引数は新しいクラスの名前で、2 番目の引数はフィールド名のリストです。

Javaはすべてを置き換えます
Python3
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(x=1, y=2) print(p.x, p.y)>

出力
1 2>

アクセス操作

Python の名前付きタプルは、そのフィールドにアクセスする便利な方法を提供します。以下は、NamedTuple に対して Python で提供されるアクセス操作の一部です。

  • インデックスによるアクセス
  • キー名によるアクセス
  • getattr() を使用したアクセス

インデックスによるアクセス

namedtuple() の属性値は順序付けされており、インデックスによってアクセスできない辞書とは異なり、インデックス番号を使用してアクセスできます。この例では、インデックスを使用して学生にアクセスしています。

Python3
# 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>

キー名によるアクセス

辞書と同様に、キー名によるアクセスも許可されます。この例では、キー名を使用して生徒の名前にアクセスしています。

Python3
# 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() を使用したアクセス

これは、名前付きタプルとキー値を引数として指定して値にアクセスするさらに別の方法です。この例では、getattr() を使用して、指定された名前付きタプル内の学生の ID にアクセスします。

Python3
# 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>

変換操作

Namedtuple は、他のデータ型を処理するためのいくつかの便利な変換操作を提供します。 パイソン 。以下は、Python の名前付きタプルに対して提供される変換操作です。

  • _make() の使用
  • _asdict() の使用
  • ** (二重星) 演算子の使用

_make()を使用した変換

この関数は、 反復可能からのnamedtuple() 引数として渡されます。この例では、_make() を使用してリスト li をnamedtuple に変換しています。

CSSの最初の子
Python3
# 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() を使用した変換操作

この関数は戻り値を返します OrderedDict() namestuple() のマップされた値から構築されたもの。この例では、_asdict() を使用して入力リストをnamedtupleインスタンスに変換しています。

Python3
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')])>

** (二重星) 演算子の使用

この関数は、辞書をnamedtuple()に変換するために使用されます。 この例では、** を使用して入力リストを名前付きタプルに変換しています。

Python3
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 の場合:

Javaのランダム値ジェネレーター
  • _田畑
  • _交換する()
  • __新しい__()
  • __getnewargs__()

_田畑

このデータ属性は取得するために使用されます。 すべてのキー名 宣言された名前空間の。この例では、_fields を使用して、宣言された名前空間のすべてのキー名を取得しています。

Python3
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() に似ていますが、fields( という名前のターゲットは元の値を変更しません) です。この例では、_replace() を使用して名前を Nandini から Manjeet に置き換えています。

Python3
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 クラスの新しいインスタンスを返します。

Python3
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(name,age,DOB) print(Student.__new__(Student,'Himesh','19','26082003'))>

出力
Student(name='Himesh', age='19', DOB='26082003')>

__getnewargs__()

この関数は、名前付きタプルをプレーン タプルとして返します。この例では、__getnewargs__() を使用して同じことを行っています。

Python3
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')>