Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get unique values from a python list of objects

Tags:

python

list

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.

like image 898
Steven Avatar asked Sep 25 '14 16:09

Steven


People also ask

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 does unique () do in Python?

unique() function. The unique() function is used to find the unique elements of an array. Returns the sorted unique elements of an array.


3 Answers

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.

like image 72
Ffisegydd Avatar answered Oct 19 '22 04:10

Ffisegydd


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']
like image 1
Padraic Cunningham Avatar answered Oct 19 '22 04:10

Padraic Cunningham


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.

like image 1
S Habeeb Ullah Avatar answered Oct 19 '22 03:10

S Habeeb Ullah