Получить объект из списка python - PullRequest
0 голосов
/ 16 апреля 2020

У меня есть три класса, определенных следующим образом:

# class that identify a single person
class Person(object):
    def __init__(self, name, surname, email):
        self.name = name
        self.surname = surname
        self.email = email

    def __eq__(self, other):
        if isinstance(other, str):
            return self.email = other
        elif isinstance(other, Person):
            return self.email = other.email


#class that allow iteration of class People
class PeopleIterator(object):
    def __init__(self, people_list):
        self._iterable = people_list
        self._index = 0

    def __next__(self):
        if self._index < (len(self._iterable.list)):
            result = self._iterable.list[self._index]
            self._index += 1
            return result
        raise StopIteration


#class that identify a list of person
class People(object):
    def __init__(self):
        self.list = []

    def add(self, obj):
        self.list.append(obj)

    def __iter__(self):
        return PeopleIterator(self)

    def __len__(self):
        return len(self.list)

По сути, это список экземпляров класса Person, который можно повторять. С помощью этого кода я могу написать:

friends = People()

john = Person("John", "Smith", "john.smith@mail.com")
friends.add(john)

mark = Person("Mark", "Green", "mark.green@mail.com")
friends.add(mark)

for f in friends:
    print(f.email)

Теперь я хотел бы получить предмет из коллекции, поиск по электронной почте. Что-то вроде:

if friends["john.smith@mail.com"] is not None:
    print(friends["john.green@mail.com"].name)

david = friends["david.white@mail.com"]
if david is None:
    print("David is not your friend")

Я не уверен, было ли словарь лучшим решением вместо списка.

Ответы [ 2 ]

2 голосов
/ 16 апреля 2020

Вы должны реализовать метод __getitem__ в классе People:

def __getitem__(self, item):
    try:
        return [x for x in self.list if x.email == item][0]
    except IndexError:
        return None
0 голосов
/ 16 апреля 2020

Вы также можете использовать базу данных. Здесь MongoDB ( скачать , учебник ). Это лучше для больших данных и более сложного анализа.

    import pymongo
    from pymongo import MongoClient

    mongoclient = MongoClient("mongodb://localhost:27017/")  #Connect to Mongodb

    database    = mongoclient["yourdatabase"]  #Connects to the database
    collection  = database["youcollection"]  #Connects to the collection

    element1     = {"firstname": "John", "lastname": "Smiht", "email": "john.smith@mail.com"} #Element to insert
    collection.insert_one(element1)  #Insert in collection

    element2     = {"firstname": "Mark", "lastname": "Green", "email": "mark.green@mail.com"} #Element to insert
    collection.insert_one(element2)  #Insert in collection

    results      = collection.find({"email": "john.smith@mail.com"})  #Write Element in collection

    for result in results:  #Results is a array of all elements which were found
        print(result["firstname"])  #Print the firstname of the found element
        print(result["lastname"])  #print the lastname of the found element
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...