当前位置: 首页 » Python(人生苦短) » py_basic » set–列表求交集、并集、差集

set–列表求交集、并集、差集

[文章目录] x

python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算。sets 支持 x in set, len(set),和 for x in set。作为一个无序的集合,sets不记录元素位置或者插入点。因此,sets不支持 indexing, slicing, 或其它类序列(sequence-like)的操作。

1. 获取两个list 的交集

2. 获取两个list 的并集

3. 获取两个 list 的差集

 

讨论:

因为set以后,list变得无序了,但是仍旧想保留list之前的顺序

 now should keep the order, but there is another solution for Python 2 and 3:
<span class="pun">>>></span><span class="pln"> x </span><span class="pun">=</span> <span class="pun">[</span><span class="lit">1</span><span class="pun">,</span> <span class="lit">2</span><span class="pun">,</span> <span class="lit">20</span><span class="pun">,</span> <span class="lit">6</span><span class="pun">,</span> <span class="lit">210</span><span class="pun">]</span><span class="pun">>>></span><span class="pln"> sorted</span><span class="pun">(</span><span class="pln">set</span><span class="pun">(</span><span class="pln">x</span><span class="pun">),</span><span class="pln"> key</span><span class="pun">=</span><span class="pln">x</span><span class="pun">.</span><span class="pln">index</span><span class="pun">)</span><span class="pun">[</span><span class="lit">1</span><span class="pun">,</span> <span class="lit">2</span><span class="pun">,</span> <span class="lit">20</span><span class="pun">,</span> <span class="lit">6</span><span class="pun">,</span> <span class="lit">210</span><span class="pun">]>>> a =[1, 2, 'a']>>> b=[2]>>> sorted((set(a)-set(b)),key=a.index)[1, 'a']</span>[/crayon]
 

参考资料:
http://blog.chinaunix.net/uid-200142-id-3992553.html
http://blog.csdn.net/business122/article/details/7541486


下一篇 :

上一篇 :

暂无评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注

$(document).ready(function(){ $("#article-index").css('display','none');});