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.
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With