python获取两个列表的交集

python获取两个列表的交集方法分享

方法一

遍历其中一个列表检查当前遍历的元素是否存在于另外一个列表,如果存在那么将其加入到结果集中,得出的结果既是两个列表的“交集”部分

# -*- coding: utf-8 -*-

list1 = ['5118', '站长之家', '爱站', 'Ahref', 'link114', '超级蜘蛛池']
list2 = ['MOZ', 'archive', 'semrush', '5118', '站长之家', '爱站']

for element in list1:
    if element in list2:
        print(element)

运行结果:

5118
站长之家
爱站

方法二

将两个列表转换为set集合,然后使用集合操作符&求解两个set集合的交集

# -*- coding: utf-8 -*-

list1 = ['5118', '站长之家', '爱站', 'Ahref', 'link114', '超级蜘蛛池']
list2 = ['MOZ', 'archive', 'semrush', '5118', '站长之家', '爱站']

result = set(list1) & set(list2)
# 也可以直接转换为列表
# result = list(set(list1) & set(list2))
print(result)
 

运行结果:

{'爱站', '站长之家', '5118'}

方法三

前面的例子中两个list都是简单的单元素列表,如果列表中有嵌套类型的可以参考如下代码:

# -*- 编码: utf-8 -*-

b1=[1,2,3]
b2=[[2,4],[3,5]]
b3 = [filter(lambda x: x in b1,sublist) for sublist in b2]
print b3

运行结果:

[2, 3]

给TA打赏
共{{data.count}}人
人已打赏
python笔记

python转换Unix时间戳

2022-5-4 13:46:17

python笔记

python爬虫报错:(Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1129)')))解决

2022-6-26 22:42:04

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索