Python 是否有一种更为通灵的方法来防止向列表中添加重复项?
有没有更简洁的方法来防止在列表中添加重复项Python 是否有一种更为通灵的方法来防止向列表中添加重复项?,python,list,Python,List,有没有更简洁的方法来防止在列表中添加重复项 if item not in item_list: item_list.append(item) 或者这实际上是一个便宜的操作?您可以使用如下所示的内置set()函数和list()函数将该set对象转换为普通python列表: item_list = ['a','b','b'] print list(set(item_list)) #['a', 'b'] 注意:使用集合时不维护顺序使用集合来跟踪看到的项目 如果顺序不重要,只需在项目列表上
if item not in item_list:
item_list.append(item)
或者这实际上是一个便宜的操作?您可以使用如下所示的内置
set()
函数和list()
函数将该set对象转换为普通python列表:
item_list = ['a','b','b']
print list(set(item_list))
#['a', 'b']
注意:使用集合时不维护顺序使用集合来跟踪看到的项目 如果顺序不重要,只需在
项目列表上使用set()
:
>>> set(item_list)
set([1, 100, 7, 11, 14, 4])
由于@hcwsha的原始解决方案已被替换,我在这里记录它:
seen = set(item_list)
# [...]
if item not in seen:
seen.add(item)
item_list.append(item)
这在O(1)中运行,因此可以认为比您当前使用的更好。您的方式很棒!集合对于这类事情很有用,但正如前面提到的,它们不能维持秩序。其他更简洁的写作方式,尽管可能不那么清晰,如下所示:
item_list.append(item) if item not in item_list else None
及
如果您想添加多个new_items=[item1,…]
像这样,可以修改最后一个
item_list += [item for item in new_items if item not in item_list]
如果在多个位置向集合追加数据,则编写样板代码(如如果项不在项列表中:…
)不是很方便,您应该有一个单独的函数,使用“append”方法覆盖跟踪对集合或子类列表的更改:
class CollisionsList(list):
def append(self, other):
if other in self:
raise ValueError('--> Value already added: {0}'.format(other))
super().append(other)
l = CollisionsList()
l.append('a')
l.append('b')
l.append('a')
print(l)
例如,当列表中有对象并且需要检查某个属性以查看该属性是否已在列表中时
并不是说这是最好的解决方案,但它确实起到了作用:
def _extend_object_list_prevent_duplicates(list_to_extend, sequence_to_add, unique_attr):
"""
Extends list_to_extend with sequence_to_add (of objects), preventing duplicate values. Uses unique_attr to distinguish between objects.
"""
objects_currently_in_list = {getattr(obj, unique_attr) for obj in list_to_extend}
for obj_to_add in sequence_to_add:
obj_identifier = getattr(obj_to_add, unique_attr)
if obj_identifier not in objects_currently_in_list:
list_to_extend.append(obj_to_add)
return list_to_extend
这是一个很好的方法,它的pythonic too你可能想提一下顺序可能无法维持好的方法,这就像一个符咒,无论如何我不明白为什么要使用.add和.append。我刚刚使用了“.add”并使用list(见)将集合转换为列表。@migueloriz我想项目的顺序并不重要。如果列表包含复杂的数据结构,这是一个优雅的解决方案。
class CollisionsList(list):
def append(self, other):
if other in self:
raise ValueError('--> Value already added: {0}'.format(other))
super().append(other)
l = CollisionsList()
l.append('a')
l.append('b')
l.append('a')
print(l)
def _extend_object_list_prevent_duplicates(list_to_extend, sequence_to_add, unique_attr):
"""
Extends list_to_extend with sequence_to_add (of objects), preventing duplicate values. Uses unique_attr to distinguish between objects.
"""
objects_currently_in_list = {getattr(obj, unique_attr) for obj in list_to_extend}
for obj_to_add in sequence_to_add:
obj_identifier = getattr(obj_to_add, unique_attr)
if obj_identifier not in objects_currently_in_list:
list_to_extend.append(obj_to_add)
return list_to_extend