I have a class:
class Car:
make
model
year
I have a list of Cars and want to get a list of unique models among my Cars.
The list is potentially tens of thousands of items. What's the best way to do this?
Thanks.
I have a class:
class Car:
make
model
year
I have a list of Cars and want to get a list of unique models among my Cars.
The list is potentially tens of thousands of items. What's the best way to do this?
Thanks.
Use a set comprehension. Sets are unordered collections of unique elements, meaning that any duplicates will be removed.
cars = [...] # A list of Car objects.
models = {car.model for car in cars}
This will iterate over your list cars and add the each car.model value at most once, meaning it will be a unique collection.
If you want to find cars that only appear once:
from collections import Counter
car_list = ["ford","toyota","toyota","honda"]
c = Counter(car_list)
cars = [model for model in c if c[model] == 1 ]
print cars
['honda', 'ford']
Add a method to the class that returns a unique list
def unique(list1):
# intilize a null list
unique_list = []
# traverse for all elements
for x in list1:
# check if exists in unique_list or not
if x not in unique_list:
unique_list.append(x)
return unique_list
Otherwise,
If you're looking to pass a dictionary of make, model year then you can use pandas dataframe in order to get the unique values.
Now it depends on what you mean by unique. If you mean Exactly the same object then this should work:
def check_all_objects_unique(objects: List[Any]) -> bool:
unique_objects = set(objects)
if len(unique_objects) == len(objects):
return True
elif len(unique_objects) < len(objects):
return False
If by unique you mean objects with the same attribute values then other answers on here will help you.