python 交集
- IT科技
- 关注:2.32W次
<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>
python 交集怎么操作?一起来看看小编今天的分享吧!
在数据处理中经常需要使用 Python来获取两个列表的交集,在 Python 中实现的方法有很多,以下是常用的获取交集的方法。
常规方法如下:
>>> a = [1, 2, 3, 4, 5, 6]>>> b = [2, 4, 6, 8 ,10]>>> a and b[2, 4, 6]
其他方法如下:
方法一:
intersection = list(set(a).intersection(b))
方法二:
intersection = list(set(a) & set(b))
方法三:
intersection = [x for x in b if x in set(a)] # list a is the larger list b
方法四:
intersection = list((set(a).union(set(b)))^(set(a)^set(b)))
注意:如果不考虑顺序并且一定要使用 loop 的话,不要直接使用 List,而应该使用 Set。在 List 中查找元素相对 Set 慢了非常非常多。
标签:
Python
- 文章版权属于文章作者所有,转载请注明 https://dongkepu.com/itkeji/0mjdq4.html