2012-09-07 173 views
1

有没有一种方法可以在具有多个属性的用户定义Python对象列表上迭代和调用函数?假设它被称为Entry,属性名称和年龄。映射/遍历Python对象列表

,这样我可以说的东西的

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(),但不知道这是即使在这种情况下,有效的。

+0

在'func'中访问'name'和'age'是否有原因? –

+0

为什么不把list_of_entries中的每个条目都传递给func(),然后通过传入的对象访问name/age? –

+0

来计算:“list_of_entries.name()”你可以使用map! –

回答

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] 
+0

但是最后一个会将可调用函数传递给函数,我会假设OP需要值。 – jdi

+0

我假设“.name”和“.age”是属性;如果他们是可以召唤的,那么你应该给他们打电话(在所有三个例子中)。在OP的例子中,他在列表中调用“.name()”,这没有多大意义,所以我把它当作伪代码。 –

+0

OP使用循环在 – jdi

0

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

results = [f(e.name, e.age) for e in entries] 
+0

只是让它变成parens而且你也得到了一个生成器 - 如果想懒惰地评估您的列表,因为你需要物品。 – underrun

0

如果姓名和年龄是唯一的两个属性,您可以使用增值税。否则,将** 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)