Python 如果在列表中,则返回列表中的对象
我想知道是否有一种类似蟒蛇的方法可以做到以下几点:Python 如果在列表中,则返回列表中的对象,python,list,unique,Python,List,Unique,我想知道是否有一种类似蟒蛇的方法可以做到以下几点: if check_object in list_of_objects: return #the object from list else: return check_object 如果在列表中找到匹配的对象,我可以在列表中进行迭代以找到匹配的对象,但这似乎有点过分了,有没有更符合python的方法呢 x = ['a', 'b', 'c'] if 'b' in x: print x[x.index('b')] else
if check_object in list_of_objects:
return #the object from list
else:
return check_object
如果在列表中找到匹配的对象,我可以在列表中进行迭代以找到匹配的对象,但这似乎有点过分了,有没有更符合python的方法呢
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'
我想这会有用的
try:
idx = list_of_objects.index(check_object)
return list_of_objects[idx]
except ValueError:
return check_object
这样做的好处是,它只需要像其他一些解决方案所建议的那样在列表中查找一次(而不是两次)对象。而且,很多人认为“请求宽恕”比“跃跃欲试”更具说服力。(EAFP vs LBYL)“假设这两个对象是资源清册的一部分,并且您只需要每个对象的一个实例,这些对象在名称上可能被认为是相等的,但具有其他不同的属性,因此您希望重新获取已没有新对象的对象” 不过,你在这里所做的不会达到这个目的。您正在列表中查找对象的存在性,然后返回相同的对象。它们不能有不同的属性,因为您正在测试身份而不是平等性 您最好将
对象列表
替换为对象目录
,并根据对象的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
因此,检查列表中是否存在始终会返回与匹配项相同的项,而比较字典中的键可以检索不同的项。如果列表中有
check\u object
,则从列表中返回该对象相当于返回check\u object
。不管怎样,为什么不返回check_object
?假设这两个对象是库存的一部分,并且每个对象只需要一个实例,这些对象在名称上可能被认为是相等的,但有其他不同的属性,因此您希望重新生成已没有新对象的对象如果check对象是内存占用对象,我不希望同时存在两个相同的版本,我宁愿让一个对象被垃圾收集,而只使用另一个。一般来说,如果你发现自己经常做这种事情,那么你就没有给你的类正确的平等定义。@BrenBarn让我们假设list\u 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