Namedtuple בפייתון

Python תומך בסוג של מילון מיכל הנקרא ' namedtuple() 'נוכח במודול' אוספים '. במאמר זה אנו הולכים לראות כיצד ליצור NameTuple ופעולות על NamedTuple.

מה זה NamedTuple ב-Python?

ב פִּיתוֹן NamedTuple קיים בתוך מודול אוספים . הוא מספק דרך ליצור מבני נתונים פשוטים קלים הדומים למחלקה אך ללא תקורה של הגדרת מחלקה מלאה. כמו מילונים, הם מכילים מפתחות המועברים לערך מסוים. להיפך הוא תומך הן בגישה מ-key-value והן באיטרציה בפונקציונליות ש מילונים חוֹסֶר.

תחביר Python NamedTuple

namedtuple(typename field_names)

  • typename - שם ה-namedtuple.
  • field_names - רשימת התכונות המאוחסנות ב-namedtuple.

דוּגמָה: יישום קוד של 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
  • פעולות גישה
  • פעולות המרה
  • פעולות נוספות

צור NameTuple ב-Python

זה יוצר מחלקת namedtuple חדשה באמצעות הפונקציה namedtuple() מה- אוספים מודול. הארגומנט הראשון הוא שם המחלקה החדשה והארגומנט השני הוא רשימה של שמות שדות.

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

תְפוּקָה
1 2  

פעולות גישה

Namedtuples ב-Python מספקים דרכים נוחות לגשת לשדות שלהם. להלן כמה פעולות גישה הניתנות ב-Python עבור NamedTuple:

  • גישה לפי אינדקס
  • גישה לפי שם מפתח
  • גישה באמצעות 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()

זוהי דרך נוספת לגשת לערך על ידי מתן ערך namedtuple ו-key בתור הארגומנט שלו. בדוגמה זו אנו משתמשים ב-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 getattr()   print  (  'The Student DOB using getattr() is : '     end  =  ''  )   print  (  getattr  (  S     'DOB'  ))   

תְפוּקָה
The Student DOB using getattr() is : 2541997  

פעולות המרה

Namedtuples מספקים כמה פעולות המרה שימושיות לעבודה עם סוגי נתונים אחרים פִּיתוֹן . להלן פעולות ההמרה הבאות הניתנות עבור namedtuples ב- Python:

  • שימוש ב-_make()
  • שימוש ב-_asdict()
  • שימוש באופרטור ** (כוכב כפול).

המרה באמצעות _make()

פונקציה זו משמשת להחזרת א namedtuple() מה-Iterable עבר כטיעון. בדוגמה זו אנו משתמשים ב-_make() כדי להמיר את הרשימה 'li' ל-namedtuple.

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() כפי שנבנה מהערכים הממופים של namedtuple(). בדוגמה זו אנו משתמשים ב-_asdict() כדי להמיר את רשימת הקלט למופע 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 _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(). בדוגמה זו אנו משתמשים ב-'**' כדי להמיר את רשימת הקלט ל-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() אבל מטרות שדות בשם (לא משנה את הערכים המקוריים). בדוגמה זו אנו משתמשים ב-_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 על ידי לקיחת הערכים שאנו רוצים להקצות למפתחות ב-tuple בעל השם. בדוגמה זו אנו משתמשים ב-__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__()

פונקציה זו מחזירה את ה-tuple בשם כ-tuple רגיל. בדוגמה זו אנו עושים את אותו הדבר באמצעות __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. שיטות : מחלקות יכולות להכיל מתודות (פונקציות) while namedtuple מספקת בעיקר דרך לאחסן נתונים עם שדות בעלי שם.
  3. יְרוּשָׁה : מחלקות תומכות בירושה המאפשרות יצירת היררכיות מורכבות ואילו namedtuple אינו תומך בירושה.

מה ההבדל בין dict מוקלד ל-namedtuple?

  1. בדיקת סוג : TypedDict (מה typing מודול) מספק רמזים לסוגים עבור מילונים עם צמדי מפתח-ערך ספציפיים שימושיים לבדיקת סוגים. namedtuple אינו מספק רמזים לסוג.
  2. השתנות : TypedDict מופעים ניתנים לשינוי ומאפשרים שינויים בערכים while namedtuple מופעים בלתי ניתנים לשינוי.
  3. מִבְנֶה : TypedDict משמש להגדרת המבנה של מילונים עם סוגים ספציפיים עבור כל מפתח ואילו namedtuple מספק שדות בעלי שם עבור נתונים דמויי tuple.