0

次のことを行うためのpythonicな方法があるかどうか疑問に思っていました:

if check_object in list_of_objects:
    return #the object from list
else:
    return check_object

リスト内で見つかった場合、一致するオブジェクトを見つけるためにリストを反復処理できますが、それはやり過ぎのように思えます。これを行うためのよりPythonicな方法はありますか?

4

4 に答える 4

1
x = ['a', 'b', 'c']
if 'b' in x:
    print x[x.index('b')]
else:
    print 'not found'

オブジェクト自体を返すこともできます。Python >= 2.4 で動作:

print 'a' in x and 'a' or 'not found'
于 2012-08-22T17:11:10.383 に答える
0

これはうまくいくと思います...

try:
    idx = list_of_objects.index(check_object)
    return list_of_objects[idx]
except ValueError:
    return check_object

これには、他のソリューションのいくつかが示唆するように、リスト内のオブジェクトを (2 回ではなく) 1 回検索するだけでよいという利点があります。また、多くの人は、「ジャンプする前に見る」よりも「許しを求める」方がよりパイソン的だと考えています。(EAFP 対 LBYL)

于 2012-08-22T17:31:51.120 に答える
0

「2 つのオブジェクトがインベントリの一部であり、各オブジェクトの 1 つのインスタンスのみが必要であるとします。オブジェクトは名前が同じであると見なされますが、他の異なる属性を持っているため、新しいオブジェクトではなく、既に持っているオブジェクトを返したいとします。」

ただし、ここで行っていることはそれを達成しません。リスト内のオブジェクトの存在を探してから、同じオブジェクトを返します。同一性をテストしており、平等ではないため、異なる属性を持つことはできません。

オブジェクトの ID または名前に基づいて置き換えlist_of_objectsてルックアップを行う方がよい場合があります。dict_of_objects

# Example class with identifier
class ExampleObject(object):
    def __init__(self, name):
        self.name = name

example1 = ExampleObject('one')

# Object Registry: just convenience methods on a dict for easier lookup
class ObjectRegistry(dict):
    def register(self, object):
        self[object.name] = object

    def lookup(self, object):
        name = getattr(object, 'name', object)
        return self.get(name, object)

# Create the registry and add some objects
dict_of_objects = ObjectRegistry()
dict_of_objects.register(example1)

# Looking up the existing object will return itself
assert dict_of_objects.lookup(example1) is example1

# Looking up a new object with the same name will return the original
example1too = ExampleObject('one')
assert dict_of_objects.lookup(example1too) is example1

したがって、リスト内の存在をチェックすると、常に一致したアイテムと同じアイテムが返されますが、辞書内のキーを比較すると、別のアイテムを取得できます。

于 2012-08-23T02:43:04.930 に答える
-2
return check_object if check_object in list_of_objects else None
于 2012-08-22T17:13:57.963 に答える