Search code examples
pythondictionarypython-itertoolsfunctools

Map/Iterating through List of Python Object


Is there a way to iterate and call a function on a list of user-defined Python objects with multiple attributes? Let's suppose it's called Entry, with attribute name, and age.

Such that I can say something to the effect of

def func(name, age):
    //do something

def start(list_of_entries)
    map(func, list_of_entries.name(), list_of_entries.age()) 
    //but obviously the .name and .age of the object, not the iterable
    //these are the only two attributes of the class

Was thinking about using functools.partial() but not sure if that is even valid in this case.


Solution

  • I suppose you could use a lambda function:

    >>> def start(list_of_entries):
    ...     map((lambda x:func(x.name,x.age)), list_of_entries)
    

    But why not just use a loop?:

    >>> def start(list_of_entries):
    ...     for x in list_of_entries: func(x.name, x.age)
    

    or if you need the results of func:

    >>> def start(list_of_entries):
    ...     return [func(x.name, x.age) for x in list_of_entries]