可变数量的列表的交集

编程入门 行业动态 更新时间:2024-10-15 20:20:40
本文介绍了可变数量的列表的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我定义了两个列表的交集,如下所示:

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 :

>> >列表= [[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)))

更多推荐

可变数量的列表的交集

本文发布于:2023-11-29 12:29:23,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数量   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!