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.
Use set comprehension . Sets are unordered collections of unique items, which means that any duplicates will be deleted.
set
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.
car.model
cars
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']
Source: https://habr.com/ru/post/1203416/More articles:Python matplotlib.stem without markers - pythonHow to handle or throw a BlockedIndefinitelyOnSTM exception? - multithreadinghttps://translate.googleusercontent.com/translate_c?depth=1&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1203413/how-to-find-two-matched-id-in-two-files-and-then-use-their-values-to-calculate&usg=ALkJrhirHDPvTI1Gh5cnBWJmtVNqWxlEVwDisplay contact properties if it has more than one phone number with ios8 - iosCreate a Certificate Signing Request (CSR) with Go - sslDoes the expression `new T` express rvalue or lvalue? - c ++Format your phone number with Twig - phpC ++ 11: Does the assignment operator provide the POD type, which is the POD, and thus is globally initialized? - c ++Encoding and decoding RSA using private key? - androidHow can I get the referent for connecting socket.io - node.jsAll Articles