python - 可变数量列表的交集

标签 python list function set intersection

我定义两个列表的交集如下:

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]

最佳答案

使用 *-list-to-argument operator并使用 set.intersection 代替您的自定义函数:

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

如果你想在一个函数中实现列表到设置到列表的逻辑,你可以这样做:

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

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

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

关于python - 可变数量列表的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10861236/

相关文章:

python - 检测物体并获得平均像素值(BGR)

python - Sphinx 描述 api 的有效输入值

java - 删除列表中的重复记录

python - 在 python 中搜索嵌套列表

c# - 在 C# 中使用 List<> 作为 BindingSource

postgresql - 如何使函数在 postgreSQL 中使用 CASE 和 IFNULL?

java - GridLayout 在应该显示的时候没有显示在框架上

python - 使成排的 Sprite 重新出现在pygame的屏幕顶部

python zipfile目录也被复制

javascript - 从 for 循环中的函数返回值