Skip to main content
 首页 » 编程设计

python之映射/遍历 Python 对象列表

2025年05月04日15zengkefu

有没有一种方法可以在具有多个属性的用户定义的 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() 但不确定在这种情况下是否有效。

请您参考如下方法:

我想你可以使用 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]