class Shape():
def __init__(self, n_sides, name):
self.n_sides = n_sides
self.name = name
def generate_shapes():
return [Shape(4, 'square'), Shape(3, 'triangle'), Shape(4, 'rectangle')]
def generate_one_shape():
return Shape(4, 'square')
shapes = generate_shapes()
one_shape = generate_one_shape()
shapes.index(one_shape)
list.index()はオブジェクトを表面的に比較するので、次のようなエラーが発生します。オブジェクトの状態の等価性に基づいてリスト内のオブジェクトのインデックスを取得します。
Traceback (most recent call last):
File "list_remove_object_by_value.py", line 14, in <module>
shapes.index(one_shape)
ValueError: <__main__.Shape instance at 0x7efffbbcec68> is not in list
がどのように私はそれを有するクラスの形の別のインスタンスを使用して効率的にリスト内のクラスShapeのインスタンスのインデックスを取得することができますように私は、インデックスを返すためにlist.index(one_shape)を希望属性の値は?
Shapeに '__eq__'を定義してみてください – Hamms
*複数の*要素がある場合や* none *の場合はどうなりますか? –
このようなインスタンスが複数ある場合は、リストの最初の要素のインデックスのみが必要です。 –