如何使用另一个列表使用列表推导对列表进行子集化

时间:2017-05-11 11:10:57

标签: python list list-comprehension

我有一个很大的字典列表,我想要分组,如下所示:

first_list = [{'name':'James','gender':'M','address':'California'},{'name':'Tom','gender':'M','address':'California'},
{'name':'Jane','gender':'F','address':'Utah'},
{'name':'Kim','gender':'F','address':'Wisconsin'},
{'name':'Ron','gender':'M','address':'Montana'}]

我有另一个名单:

second_list = ['James', 'Tom']

我希望列出名称'在第一个列表中不是第二个列表的一部分,它只是删除了James和Tom词典。

[{'name':'Jane','gender':'F','address':'Utah'},
{'name':'Kim','gender':'F','address':'Wisconsin'},
{'name':'Ron','gender':'M','address':'Montana'}]

我尝试使用列表理解,但我不认为这适用于不同的列表:

third_list = [x for x in first_list if x['name'] != (y for y in second_list)] 

这不会起作用,将返回与第一个列表相同的列表。我的语法错了吗?

3 个答案:

答案 0 :(得分:2)

使用适合您的not in

third_list = [i for i in first_list if i['name'] not in second_list]

<强>结果

[{'address': 'Utah', 'gender': 'F', 'name': 'Jane'},
 {'address': 'Wisconsin', 'gender': 'F', 'name': 'Kim'},
 {'address': 'Montana', 'gender': 'M', 'name': 'Ron'}]

答案 1 :(得分:0)

您的代码不起作用,因为(y for y in second_list)是一个生成器,x['name']是一个字符串,这意味着它将一直返回False,我想你想要的是这个:

>>> first_list = [{'name':'James','gender':'M','address':'California'},{'name':'Tom','gender':'M','address':'California'},
... {'name':'Jane','gender':'F','address':'Utah'},
... {'name':'Kim','gender':'F','address':'Wisconsin'},
... {'name':'Ron','gender':'M','address':'Montana'}]
>>>
>>>
>>> second_list = ['James', 'Tom']
>>>
>>> [x for x in first_list if x['name'] not in second_list]
[{'gender': 'F', 'name': 'Jane', 'address': 'Utah'}, {'gender': 'F', 'name': 'Kim', 'address': 'Wisconsin'}, {'gender': 'M', 'name': 'Ron', 'address': 'Montana'}]

Pythonic方法,尝试使用filter方法:

>>> filter(lambda x:x["name"] not in second_list,first_list)
[{'gender': 'F', 'name': 'Jane', 'address': 'Utah'}, {'gender': 'F', 'name': 'Kim', 'address': 'Wisconsin'}, {'gender': 'M', 'name': 'Ron', 'address': 'Montana'}]

答案 2 :(得分:0)

使用

third_list = [x for x in first_list if x['name'] not in second_list]