如何使用dict
(因为它的键是唯一的)?
假设我们有
class Object:
def __init__(self, id):
self.id = id
Aobject = Object(1)
Bobject = Object(1)
Cobject = Object(2)
objects = [Aobject, Bobject, Cobject]
然后可以使用Python 3中的理解生成list
具有Object
唯一字段的 sid
dict
unique_objects = list({object_.id: object_ for object_ in objects}.values())
在Python 2.7中
unique_objects = {object_.id: object_ for object_ in objects}.values()
在Python <2.7中
unique_objects = dict([(object_.id, object_) for object_ in objects]).values()
最后,我们可以编写函数(Python 3版本)
def unique(elements, key):
return list({key(element): element for element in elements}.values())
whereelements
可能是 anyiterable
并且key
是一些从(在我们的特定情况下等于)callable
返回hashable
对象的地方。elements
key
operator.attrgetter('id')
Marcin 的答案工作正常,但对我来说看起来不像 Pythonic,因为列表理解会seen
从外部范围改变对象,使用set.add
方法并将其结果(即None
)与obj
.
最后但同样重要的部分:
基准
setup = '''
import random
class Object:
def __init__(self, id):
self.id = id
objects = [Object(random.randint(-100, 100))
for i in range(1000)]
'''
solution = '''
seen = set()
result = [seen.add(object_.id) or object_
for object_ in objects
if object_.id not in seen]
'''
print('list comprehension + set: ',
min(timeit.Timer(solution, setup).repeat(7, 1000)))
solution = '''
result = list({object_.id: object_
for object_ in objects}.values())
'''
print('dict comprehension: ',
min(timeit.Timer(solution, setup).repeat(7, 1000)))
在我的机器上给
list comprehension + set: 0.20700953400228173
dict comprehension: 0.1477799109998159