if-in-list返回lis中的对象

2024-03-29 15:58:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否有一种Python式的方法来完成以下任务:

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

如果在列表中找到了匹配的对象,我可以在列表中进行迭代以找到匹配的对象,但这似乎有点过头了,有没有一种更像python的方法呢?在


Tags: ofthe对象方法infrom列表return
3条回答
x = ['a', 'b', 'c']
if 'b' in x:
    print x[x.index('b')]
else:
    print 'not found'

也可以返回对象本身。使用python>;=2.4:

^{pr2}$

我想这会管用。。。在

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

这样做的好处是它只需要像其他一些解决方案建议的那样在列表中查找一次(而不是两次)。而且,许多人认为“请求原谅”比“先看后跳”更像Python。(EAFP与LBYL)

假设这两个对象是清单的一部分,而您只需要每个对象的一个实例,这两个对象可能被认为是相同的,但有其他不同的属性,因此您想重新查找已经没有新对象的对象

不过,你在这里所做的不会达到这个目的。你在一个列表中寻找一个对象的存在,然后返回相同的对象。它们不能有不同的属性,因为你在测试同一性和不相等性。在

最好将list_of_objects替换为dict_of_objects,并根据对象的ID或名称进行查找:

# 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

因此,检查列表中是否存在将始终返回与匹配项相同的项,而在字典中比较键可以检索到不同的项。在

相关问题 更多 >