Python 两个list 求交集,并集,差集

在python中,分别求两个list 的交集,并集与差集,怎么实现比较方便呢?
除了两个for 循环, 还有其余的更方便的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/python
#coding:utf-8

def diff(listA,listB):
#求交集的两种方式
retA = [i for i in listA if i in listB]
retB = list(set(listA).intersection(set(listB)))

print "retA is: ",retA
print "retB is: ",retB

#求并集
retC = list(set(listA).union(set(listB)))
print "retC1 is: ",retC

#求差集
retD = list(set(listB).difference(set(listA)))+list(set(listA).difference(set(listA)))
print "retD is: ",retD

retD_new = list(set(listA)^set(listB))

retE = [i for i in listB if i not in listA]
print "retE is: ",retE

def main():
listA = [1,2,3,4,5]
listB = [3,4,5,6,7]
diff(listA,listB)

if __name__ == '__main__':
main()

大体上是两种思路:
1.使用列表解析式. 列表解析式一般来说比循环更快.
2.将list转成set以后,使用set的各种方法去处理.

Comments

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×