Frage

set https://docs.python.org/2/library/sets.html#sets.Set

I have a list of 10000 class objects(django model). although they are all unique but I want to shrink this list on the basis of a class attribute.

class mymodel():
     field1 = 
     field2 = 

objects I got is different on the basis of field2. but I want to shrink on the basis of field1. field1 is common for few objects for example current list have 10000 objects. if I shrink it by the field1 it will contain around 3000 unique objects.

I dont think set provide a facility for this? any other function or approach?

War es hilfreich?

Lösung 2

result = []
seen = set()
for obj in objects:
    if obj.field1 not in seen:
        seen.add(obj.field1)
        result.append(obj)

Andere Tipps

Is your "list" of django objects a queryset? If so a quicker, less memory intensive approach would be to run a distinct query

objects.order_by('field1').distinct('field1')
  • Please note, this only works with PostgreSQL

I took a different approach using a dictionary comprehension.

unique_objs = {obj.field1:obj for obj in objects}.values()
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top