【Python】 Python ~ namedtuple / 簡易クラス ~

■ はじめに

https://dk521123.hatenablog.com/entry/2011/03/29/234236

のように .NET の タプルのような機能を Python で探していたら
namedtuple (名前付きタプル)に検索に引っかかったので調べてみた

■ namedtuple

公式サイト
https://docs.python.org/ja/3/library/collections.html#collections.namedtuple
用途

* 簡易的なクラスを作成できる

=> 別になくても作れるけど、どうせなら奇麗に作りたいよねって機能

■ サンプル

例1:座標
例2:ファイル情報

例1:座標

from collections import namedtuple

# ここで namedtuple を定義
Point = namedtuple('Point', ['x', 'y'])
point = Point(11, y=22)

print("({}, {})".format(point.x, point.y))

出力結果

(11, 22)

例2:ファイル情報

from collections import namedtuple

FileInfo = namedtuple('FileInfo', ['date', 'file_name', 'full_path'])

file_list = []
file_list.append(FileInfo('2020/11/12', 'sample1.jpg', r'C:\tmp\sample3\sample1.jpg'))
file_list.append(FileInfo('2021/10/12', 'sample2.jpg', r'C:\tmp\sample3\sample2.jpg'))
file_list.append(FileInfo('1922/11/12', 'sample3.jpg', r'C:\tmp\sample3\sample3.jpg'))
file_list.append(FileInfo('2020/10/12', 'sample2.jpg', r'C:\tmp\sample3\sample2.jpg'))
file_list.append(FileInfo('2002/11/12', 'sample3.jpg', r'C:\tmp\sample3\sample3.jpg'))

# 同じファイル名のファイルがあった場合、最新のものをピックアップする
target_file_list = []
for index, file_info in enumerate(file_list):
  if (index == 0):
    target_file_list.append(file_info)
    continue

  # もう少しうまく書きたいし、書けるはず、、、
  removing_file = None
  is_same_name = False
  for target_file in target_file_list:
    if (target_file.file_name == file_info.file_name):
      is_same_name = True
      if (target_file.date < file_info.date):
        removing_file = target_file
        break

  if (removing_file is not None):
    target_file_list.remove(removing_file)
    target_file_list.append(file_info)
  elif (is_same_name):
    print("Skip")
  else:
    target_file_list.append(file_info)

for target_file_info in target_file_list:
  print("({}, {}, {})".format(
    target_file_info.date, target_file_info.file_name, target_file_info.full_path))

file_name_list = [file_info.file_name for file_info in target_file_list]
for file_name in file_name_list:
  print("File name = {}".format(file_name))

print("Done")

出力結果

Skip
(2020/11/12, sample1.jpg, C:\tmp\sample3\sample1.jpg)
(2021/10/12, sample2.jpg, C:\tmp\sample3\sample2.jpg)
(2002/11/12, sample3.jpg, C:\tmp\sample3\sample3.jpg)
File name = sample1.jpg
File name = sample2.jpg
File name = sample3.jpg
Done

参考文献

https://qiita.com/tag1216/items/19fbc1a4f6a24dd7861b

関連記事

Python ~ 基本編 / クラス・継承 ~
https://dk521123.hatenablog.com/entry/2019/08/29/220537
Python ~ 基本編 / タプル・集合 ~
https://dk521123.hatenablog.com/entry/2019/10/26/000000
Python ~ 基本編 / ラムダ lambda ~
https://dk521123.hatenablog.com/entry/2019/09/23/000000