1

有没有办法在具有多个属性的用户定义 Python 对象列表上迭代和调用函数?假设它名为Entry,具有属性名称和年龄。

这样我可以说一些大意的东西

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

正在考虑使用 functools.partial() 但不确定在这种情况下是否有效。

4

3 回答 3

7

我想你可以使用 lambda 函数:

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

但为什么不只使用循环呢?:

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

或者如果您需要 func 的结果:

>>> def start(list_of_entries):
...     return [func(x.name, x.age) for x in list_of_entries]
于 2012-09-07T22:46:49.350 回答
0

您可以使用 operator.attrgetter() 允许指定多个属性,但显式列表理解更好:

results = [f(e.name, e.age) for e in entries]
于 2012-09-07T22:51:04.280 回答
0

如果 name 和 age 是仅有的两个属性,您可以使用 vars。否则,将 **kwargs 添加到您的 func 并忽略其余部分。

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)
于 2012-09-07T22:56:16.477 回答