从查询集中不存在的对象集中删除项

时间:2014-12-22 06:15:05

标签: python

Ordered会返回unordered_groups ...

的子集

Items根据unordered groupsordered进行排序。我想弄清楚如何移除itemsordered中不存在的任何项目,但我们无法确定从哪里开始。

unordered_groups = connect().get_delivery_groups_for_season(self.division_id, self.id)
ordered = DeliveryGroupOrder.objects.filter(season=self.name.get('en'), visibility="1")
order_by_name = dict(ordered.values_list('deliverygroup', 'order'))
items = sorted(unordered_groups, key=lambda g: order_by_name.get(g.name.get('en')))

1 个答案:

答案 0 :(得分:0)

只是说,这不一定是问题,只需要一个简单的列表理解。

让空白列表a代表itemsb代表ordered

>>> a = []
>>> b = [] #Note: Do not do a = b = [], it will assign a and b to a list with the same ID
>>> 

然后,让我们填充它:

>>> import random
>>> a = [random.randint(1, 10) for i in range(10)]
>>> b = [random.randint(1, 10) for i in range(10)]
>>> a
[3, 10, 6, 9, 6, 8, 9, 10, 6, 1]
>>> b
[3, 1, 2, 6, 3, 10, 2, 2, 4, 9]
>>> 

现在,使用简单的列表理解,我们可以移除ab中不存在的项目:

>>> a = [item for item in a if item in b]
>>> a
[3, 10, 6, 9, 6, 9, 10, 6, 1]
>>>