Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of objects with a unique attribute

Tags:

python

I have a list of objects that each have a specific attribute. That attribute is not unique, and I would like to end up with a list of the objects that is a subset of the entire list such that all of the specific attributes is a unique set.

For example, if I have four objects:

object1.thing = 1
object2.thing = 2
object3.thing = 3
object4.thing = 2

I would want to end up with either

[object1, object2, object3]

or

[object1, object3, object4]

The exact objects that wind up in the final list are not important, only that a list of their specific attribute is unique.

EDIT: To clarify, essentially what I want is a set that is keyed off of that specific attribute.

like image 242
Michael Davis Avatar asked Jun 27 '13 15:06

Michael Davis


People also ask

How do I get unique values in a list of objects?

By using set() method Then we extract the unique values from the list by applying the set() function. Now declare a variable 'z' and use the list() function. Once you will print 'z' then the output will display the unique values.

How do I get unique items from a list in Python?

Using Python's import numpy, the unique elements in the array are also obtained. In the first step convert the list to x=numpy. array(list) and then use numpy. unique(x) function to get the unique values from the list.

What do you call the attributes that create unique object in Python?

An instance/object attribute is a variable that belongs to one (and only one) object. Every instance of a class points to its own attributes variables. These attributes are defined within the __init__ constructor.

Is list unique in Python?

A list in python can contain elements all of which may or may not be unique. But for a scenario when we need unique elements like marking the attendance for different roll numbers of a class.


1 Answers

You can use a list comprehension and set:

objects = (object1,object2,object3,object4)
seen = set()
unique = [obj for obj in objects if obj.thing not in seen and not seen.add(obj.thing)]

The above code is equivalent to:

seen = set()
unique = []
for obj in objects:
    if obj.thing not in seen:
        unique.append(obj)
        seen.add(obj.thing)
like image 191
Ashwini Chaudhary Avatar answered Oct 11 '22 16:10

Ashwini Chaudhary