2012-12-25 44 views
5

我有一個foos對象列表。 我有一個循環來創建一個新列表。如何在python中映射2個列表並進行比較

foo1 = {id:1,location:2}
例如, foos = [foo1,foo2,foo3]

現在我想創建一個基於位置的新列表。

new_list = [] 
for foo in foos: 
    if foo.location==2: 
     new_list.append(foo) 

我想知道有沒有什麼辦法的,我可以做這樣的事情

new_list = [] 
new_list = map(if foo.location ==2,foos) // this is wrong code but is something like this possible. ? 

我可以在這裏使用地圖功能?如果是的話如何?

回答

7

當然可以用功能來做到這一點。您可以使用filterbuiltin function

new_list = filter(lambda foo: foo.location == 2, foos) 

但更普遍的和 「Python化」 的方法是使用list comprehensions

new_list = [foo for foo in foos if foo.location == 2] 
6

List comprehension似乎是要使用什麼:

new_list = [foo for foo in foos if foo.location == 2] 

map是好當你想一個函數應用於列表中的項目(或任何可迭代)和獲取列表等於(或Python3中的迭代器)作爲結果。它不能根據某些條件「跳過」項目。

1

具有u並列濾波器拉姆達功能 例如,

a = {'x': 1, 'location': 1} 
b = {'y': 2, 'location': 2} 
c = {'z': 3, 'location': 2} 
d=[a,b,c] 

按照你的例子d將是

d = [{'x': 1, 'location': 1}, {'y': 2, 'location': 2}, {'z': 3, 'location': 2}] 
output = filter(lambda s:s['location']==2,d)' 
print output' 

的結果應該是,

[{'y': 2, 'location': 2}, {'z': 3, 'location': 2}] 

我希望這可以是U預期...