pythonで自作クラスの重複のないリストを作成する
pythonで自作クラスの重複のないリストを作成する
目次
概要
コード
概要
pythonで、自作クラスをリストに詰めて、重複を除きたいことがあったので、実現方法を記します。 リスト内のリストの重複をはじくのにも使えます。
プリミティブな型をリストに詰めて重複を除外したい場合は
num_list = list() num_list.append(1) num_list.append(1) num_list.append(2) num_list = list(set(num_list)) for n in num_list: print n
結果
1 2
とできます。 しかし、自作クラスの場合は意図した動きにならなりません。
例えば、ノードの列挙で"経路"を表現するとして、経路をリストでもち、 重複する経路を除外したい場合などに有効です。
eq()のオーバーライドとかは不要で、 hash()をオーバーライドするだけです。
処理速度を気にしない場合は、メンバ変数を文字列化するだけでもオッケーです。
コード
#!/usr/bin/python # -*- coding: utf-8 -*- class MyList(list): def __init__(self): pass # def __eq__(self, other): # return self == other # # def __ne__(self, other): # return not self.__eq__(other) def __hash__(self): ''' リスト型はハッシュをもたないため、実装 文字列化してハッシュとしている ''' return hash(str(self)) def main(): route1 = MyList() # ハッシュを実装したリスト route1.append('交差点A') route1.append('交差点B') route1.append('交差点C') route1.append('交差点D') route2 = MyList() # ハッシュを実装したリスト route2.append('交差点X') route2.append('交差点Y') route2.append('交差点Z') # route2と同じ要素をもつ route3 = MyList() # ハッシュを実装したリスト route3.append('交差点X') route3.append('交差点Y') route3.append('交差点Z') route_list = list() # 通常のリスト route_list.append(route1) route_list.append(route2) route_list.append(route3) route_set = set(route_list) for route in route_set: print '-------------' for crossing in route: print crossing if __name__ == '__main__': main()
------------- 交差点X 交差点Y 交差点Z ------------- 交差点A 交差点B 交差点C 交差点D
以上