我有两个列表,其中包含相同的字典,格式如下:
清单1:
[{'url': u'http://www.bloomberg.com/news/articles/2016-08-17/you-can-get-a-50-phone-from-amazon-if-you-don-t-mind-the-ads','title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads'}, {'url': u'http://www.bloomberg.com/news/features/2016-08-18/uber-s-first-self-driving-fleet-arrives-in-pittsburgh-this-month-is06r7on', 'title': u'Uber\u2019s First Self-Driving Fleet Arrives in Pittsburgh This Month'}]清单2:
[{'url': u'http://www.bloomberg.com/news/articles/2016-08-17/you-can-get-a-50-phone-from-amazon-if-you-don-t-mind-the-ads', 'title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads'}]我想要做的是:我想删除列表1中的字典( url和title),它也存在于list2中。
我试过以下几种方法
list1[:] = [d for d in list1 if d.get('title') != (fail for fail in list2 if fail.get('title'))]但却没能做到
预期结果:
list1 = [{'url': u'http://www.bloomberg.com/news/features/2016-08-18/uber-s-first-self-driving-fleet-arrives-in-pittsburgh-this-month-is06r7on', 'title': u'Uber\u2019s First Self-Driving Fleet Arrives in Pittsburgh This Month'}]发布于 2016-08-23 05:11:23
只需做一个简单的比较:
>>> final = [i for i in one if i not in two]
>>> final
[{'url': u'http://www.bloomberg.com/news/features/2016-08-18/uber-s-first-self-driving-fleet-arrives-in-pittsburgh-this-month-is06r7on', 'title': u'Uber\u2019s First Self-Driving Fleet Arrives in Pittsburgh This Month'}]如果你真的愿意的话,你可以做list1 = final。
发布于 2016-08-23 05:11:48
如果我正确理解,您希望list1只包含标题在list2中不存在的条目。这可能最好通过两个步骤来完成,以避免对list2中的每个元素进行重复的线性扫描。
# Make a set of all titles defined by the dicts in list2
titles_in_list2 = {d['title'] for d in list2 if 'title' in d}
# Filter the contents of list1 to only items with titles not found in list2
list1[:] = [d for d in list1 if d.get('title') not in titles_in_list2]注意:如果保证所有条目都定义了一个.get键,那么第二个理解中的if调用和第一个条目中的if检查都是不需要的。.get将成为直接查找,d['title'] not in titles_in_list2,而if 'title' in d检查将被完全删除。您也不需要片分配,除非可能存在对list1的其他引用,并且必须进行更改;如果这不需要考虑,list1 = [...]就可以了。
发布于 2016-08-23 06:07:31
Burhan Khalid的回答是完美的。如果您想要一个与您以前的想法相匹配的解决方案,如下所示:
list1 = [d for d in list1 if d.get('title') not in [f.get('title') for f in list2]]
https://stackoverflow.com/questions/39092701
复制相似问题