2012-12-25 43 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预期...