我将两个列表的交集定义如下:
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]发布于 2012-06-02 17:37:56
使用set.intersection而不是自定义函数,使用*-list-to-argument operator
>>> lists = [[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 intersect(lists):
return list(set.intersection(*map(set, lists)))如果您更喜欢intersect()接受任意数量的参数,而不是单个参数,请使用以下代码:
def intersect(*lists):
return list(set.intersection(*map(set, lists)))发布于 2012-06-02 17:50:11
def intersect(*lists):
if(len(lists) <=1):
return lists[0]
result = lists[0]
for i in range(1, len(lists)):
result = set(result) & set(lists[i])
return list(result)像这样调用函数...
intersect([1,2],[2,3],[2,4])把所有的卫生都留给你。
https://stackoverflow.com/questions/10861236
复制相似问题