列表交集
返回两个列表中共同存在的元素列表。
- 从列表
a和b创建一个set。 - 使用内置的集合运算符
&仅保留同时存在于两个集合中的值,然后将set转换回list。
def intersection(a, b):
_a, _b = set(a), set(b)
return list(_a & _b)
intersection([1, 2, 3], [4, 3, 2]) # [2, 3]
返回两个列表中共同存在的元素列表。
a 和 b 创建一个 set。& 仅保留同时存在于两个集合中的值,然后将 set 转换回 list。def intersection(a, b):
_a, _b = set(a), set(b)
return list(_a & _b)
intersection([1, 2, 3], [4, 3, 2]) # [2, 3]