简体   繁体   中英

How to subset a list with list comprehension using another list

I have a large list of dictionaries I want to subset, which looks like this:

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'}]

I have another list, with names:

second_list = ['James', 'Tom']

I want to get the list where 'name' in the first list is not a part of the second list, which is simply removing James and Tom dictionaries.

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

I tried using list comprehension, but I don't think this works with different lists:

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

This won't work, will return the same list as the first list. Is my syntax wrong?

Use not in that will work for you.

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

Result

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

Your code doesn't work , because (y for y in second_list) is a generator, x['name'] is a string , which means it will return False all the time, I suppose what you want is this:

>>> 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 way to do this , try to use filter method:

>>> 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'}]

采用

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM