可变数量的列表的交集

可变数量的列表的交集

本文介绍了可变数量的列表的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了两个列表的交集,如下所示:

  def intersect(a,b):
return list (set(a)& set(b))

对于三个参数,它看起来像:

  def intersect(a,b,c):
return(list(set(a)& set(b )& set(c))

我可以将此函数推广为可变数目的列表吗?



这个调用会看起来像这样:

 >> intersect ([1,2,2],[2,3,2],[2,5,2],[2,7,2])
[2]


编辑:Python只能这样实现它?

  intersect([
[1,2,2],[2,3,2],[2,5,2],[2,7,2]
])
[2]


解决方案

使用而代之您的自定义函数使用 set.intersection

 >> >列表= [[1,2,2],[2,3,2],[2,5,2],[2,7,2]] 
>>> list(set.intersection(* map(set,lists)))
[2]

如果你想在函数内部使用list-to-set-to-list逻辑,你可以这样做:

  def交叉(列表):
返回列表(set.intersection(* map(set,lists)))

如果您更喜欢 intersect()来接受任意数量的参数而不是单个参数,请使用它:

  def intersect(* lists):
返回列表(set.intersection(* map(set,lists)))


I define intersection of two lists as follows:

def intersect(a, b):
  return list(set(a) & set(b))

For three arguments it would look like:

def intersect(a, b, c):
  return (list(set(a) & set(b) & set(c))

Can I generalize this function for variable number of lists?

The call would look for example like:

>> intersect([1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2])
[2]

EDIT: Python can only achieve it this way?

intersect([
          [1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2]
         ])
[2]
解决方案

Use the *-list-to-argument operator and instead of your custom function use set.intersection:

>>> lists = [[1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2]]
>>> list(set.intersection(*map(set, lists)))
[2]

If you want the list-to-set-to-list logic inside a function, you can do it like this:

def intersect(lists):
    return list(set.intersection(*map(set, lists)))

If you prefer intersect() to accept an arbitrary number of arguments instead of a single one, use this instead:

def intersect(*lists):
    return list(set.intersection(*map(set, lists)))

这篇关于可变数量的列表的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:52