python查找两个数组公有值

生活中经常碰到需要获取两数组公有值,那么python如何优雅获取两个数组之间的公有值,这里提供多种简单实用方法。

1.使用set元组的 &


>>> list1 = [1,2,3,4,5,6,7]
>>> list2 = [1,3, 5, 7, 9]
>>> set(list1) & set(list2)
{1, 3, 5, 7}

2.使用set元组的intersection交集


>>> list1 = [1,2,3,4,5,6,7]
>>> list2 = [1,3, 5, 7, 9]
>>> set(list1).intersection(list2)
{1, 3, 5, 7}

3.暴力查询list元素是否在第二个list中


>>> list1 = [1,2,3,4,5,6,7]
>>> list2 = [1,3, 5, 7, 9]
>>> [element for element in list1 if element in list2]
[1, 3, 5, 7]

4.实用set元组的减法


>>> list1 = [1,2,3,4,5,6,7]
>>> list2 = [1,3, 5, 7, 9]
>>> set(list1) - (set(list1)-set(list2))
{1, 3, 5, 7}
点赞

Leave a Reply

Your email address will not be published. Required fields are marked *