2012-09-07 170 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)