Map/Iterating through List of Python Object
Question
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]
OTHER TIPS
You could use operator.attrgetter() that allows to specify several attributes but explicit list comprehension is better:
results = [f(e.name, e.age) for e in entries]
If name and age are the only two attribs you can use vars. Otherwise, add **kwargs to your func and ignore the rest.
def func(name, age, **kwargs):
//do something with name and age
def start(list_of_entry):
map(lambda e: func(**vars(e)), list_of_entry)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow