0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

python イテレータ作成

Last updated at Posted at 2025-11-01

前記事の派生

イテレータとは

インスタンス自身を配列のように扱えるように

  • __iter__メソッド
  • __next__メソッド
    • 配列の各要素を定義
      を実装したクラスのこと

下記は
東海道新幹線でインスタンス生成時に指定した(のぞみ or こだま)のパラメータに応じて駅名を順に表示するクラス

ポイント

  • 全ての駅名を表示し終えたら、StopIterationメソッドで終了
    • →これがないと無限ループに
  • next()の中では、print, returnを入れているが、コンソールに出力されるのはprintによるもの、プログラム上で配列として扱えるようになるのはreturnで値として返しているため
BulletTrain.py
class BulletTrain:

    staions = {
        "common": {
            "東京出発": 0,
            "東京": 1,
            "品川": 2,
            "ここから神奈川県": 0,
            "新横浜": 3,
            "名古屋": 10,
            "ここから京都": 0,
            "京都": 13,
            "ここから大阪": 0,
            "新大阪": 14,
        },
        "nozomi": {
            "小田原": 4,
            "ここから静岡": 0,
            "熱海": 5,
            "三島": 6,
            "静岡": 7,
            "浜松": 8,
            "ここから愛知": 0,
            "豊橋": 10,
            "ここから岐阜": 0,
            "岐阜羽島": 11,
            "ここから滋賀": 0,
            "米原": 12,
        },
        "kodama": {
            "小田原": 4,
            "ここから静岡": 0,
            "熱海": 5,
            "三島": 6,
            "静岡": 7,
            "浜松": 8,
            "ここから愛知": 0,
            "豊橋": 10,
            "ここから岐阜": 0,
            "岐阜羽島": 11,
            "ここから滋賀": 0,
            "米原": 12,
            "新富士": 9,
        },
    }

    displays = []

    train = "common"

    def __init__(self, train) -> None:
        self.train = train
        # インスタンス確立時に駅名リストも確定
        self.__setDisplays__(self.__list_up__())

    def __iter__(self):
        return self

    def __next__(self) -> None:

        try:
            k, v = self.displays.pop(0)
            print(k)
            return k
        except(IndexError):
            print('到着しました。')
            raise StopIteration

    def __list_up__(self) -> list:

        if self.train not in self.staions:
            raise IndexError("選択した新幹線名は不正です。")

        if self.train == "common":
            return self.staions["common"]

        return list(self.staions["common"].items()) + list(self.staions[self.train].items())

    def __setDisplays__(self, displays) -> None:
        self.displays = self.displays + displays
$ [station for station in BulletTrain('kodama')]

出力結果

東京出発
東京
品川
ここから神奈川県
新横浜
名古屋
ここから京都
京都
ここから大阪
新大阪
小田原
ここから静岡
熱海
三島
静岡
浜松
ここから愛知
豊橋
ここから岐阜
岐阜羽島
ここから滋賀
米原
新富士
到着しました。
['東京出発', '東京', '品川', 'ここから神奈川県', '新横浜', '名古屋', 'ここから京都', '京都', 'ここから大阪', '新大阪', '小田原', 'ここから静岡', '熱海', '三島', '静岡', '浜松', 'ここから愛知', '豊橋', 'ここから岐阜', '岐阜羽島', 'ここから滋賀', '米原', '新富士']
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?