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.
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.
unique() function. The unique() function is used to find the unique elements of an array. Returns the sorted unique elements of an array.
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.
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