How to get unique values ​​from a list of python objects

I have a class:

class Car: make model year 

I have a list of cars and you want to get a list of unique models among my cars.

A list can consist of tens of thousands of items. What is the best way to do this?

Thanks.

+5
source share
2 answers

Use set comprehension . Sets are unordered collections of unique items, which means that any duplicates will be deleted.

 cars = [...] # A list of Car objects. models = {car.model for car in cars} 

This will car.model to your cars list and add each car.model value no more than once, which means it will be a unique collection.

+17
source

If you want to find cars that appear only 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'] 
+1
source

Source: https://habr.com/ru/post/1203416/


All Articles