Python の名前付きタプル

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

Python の NamedTuple とは何ですか?

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

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

namedtuple(typename field_names)

  • 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() を使用して実行できる操作です。

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

Python で NameTuple を作成する

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

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 に対して 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  

キー名によるアクセス

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

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

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

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  

変換操作

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

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

_make()を使用した変換

この関数は、 反復可能からのnamedtuple() 引数として渡されます。この例では、_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() を使用した変換操作

この関数は戻り値を返します OrderedDict() namestuple() のマップされた値から構築されたもの。この例では、_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')])  

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

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

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

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 継承はサポートされていません。

型付き辞書と名前付きタプルの違いは何ですか?

  1. 型チェック : TypedDict (から typing module) は、型チェックに役立つ特定のキーと値のペアを含む辞書の型ヒントを提供します。 namedtuple 型ヒントは提供されません。
  2. 可変性 : TypedDict インスタンスは可変であり、その間に値を変更できます。 namedtuple インスタンスは不変です。
  3. 構造 : TypedDict は、キーごとに特定のタイプを持つ辞書の構造を定義するために使用されます。 namedtuple タプルのようなデータに名前付きフィールドを提供します。