使用set()函数使用的无限制* args的自定义方法?

时间:2018-10-13 17:33:58

标签: python django function

我正在做一个项目,我们有很多这样的代码用法;

user_id     video_id    unique_watch_time
-----------------------------------------
1             v1            8       
2             v2            4       

因此,如您所见,我们在<Buffer 3f cf 9d ef bf bd 2d 0e 56 04> <Buffer 3f cf be 76 c8 b4 39 58> <Buffer 3f ef bf bd ef bf bd 3b 64 5a 1c ef bf bd> 函数中的用法与此相同。我需要使用自定义方法更改此用法。我试图编写这样的方法;

    # filtering fields are different from each other, please ignore the similarity below

def function1(self, param):
    list_x = Model1.objects.filter(foo=bar, bla=bla).values_list('field', flat=True)
    list_y = Model2.objects.filter(foo=bar, bla=bla).values_list('field', flat=True)
    lists_to_delete = set(list_x) - set(list_y) 
    # here is the code line with set() that needed to be method

    self._delete(lists_to_delete)

def function2(self, param):
    list_z = Model3.objects.filter(foo=bar, bla=bla).values_list('field', flat=True)
    list_q = Model4.objects.filter(foo=bar, bla=bla).values_list('field', flat=True).distinct()
    list_w = Model5.objects.filter(foo=bar, bla=bla).values_list('field', flat=True)
    lists_to_delete = set(list_x) - set(list_y) - set(list_w)
    # here is the code line with set() that needed to be method

    self._delete(lists_to_delete)

... # other functions continues like above
...
...

用法将有所变化;

set()

代替这个;

def _get_deleted_lists(self, *args):
   value = set()
   for arg in args:
       value |= set(arg)
   return value

但是我的自定义方法未返回与以前相同的值。我该如何实现?

1 个答案:

答案 0 :(得分:1)

对集的

|操作将返回其并集。您想要的是与众不同(-

def _get_deleted_lists(*lists):
   if not lists:
       return set()
   result = set(lists[0])
   for l in lists[1:]:
       result -= set(l)
   return result