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

标签 python django function

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

    # 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

并且用法将发生变化,例如;

lists_to_delete = self._get_deleted_lists(list_x, list_y, ...)

而不是这个;

lists_to_delete = set(list_x) - set(list_y) 

但是我的自定义方法没有返回与以前相同的值。我怎样才能实现这个目标?

最佳答案

| 对集合的操作返回它们的并集。你想要的是差异(-)

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

关于python - 使用 set() 函数使用无限 *args 的自定义方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52795565/

相关文章:

sql - 在 PostgreSQL 函数中声明并返回自定义类型

python - 头尾在一条线上

python - Python中的多线程套接字,消息报错UniUnicodeDecodeError

python - 如何中断python多线程应用程序?

python - 如何将一个列表从一个类传递到另一个类?

python - “列表”对象没有属性 'get'

数据库设计 : ordered many-to-many relationship

python - PyCharm 控制台 - 没有命名的模块

python - 创建一个字谜检查器

python - 在类变量上调用类内的 type(dict) 函数 (Python 3.4)