Python implements two list methods for intersection union and difference sets

  • 2020-12-05 17:16:42
  • OfStack

An example of Python is given to illustrate the method of two list to find intersection, union and difference sets. To share for your reference, the details are as follows:

In python, arrays can be represented as list. If you have two arrays, and you want the intersection, the union and the difference, how can you do that?

Of course, the easiest thing to think of is to loop through two arrays, writing two for loops. Most students should be able to write this way, and there is not too much technical content, this blogger will not explain. Here are some ways to use the more bility 1.

As usual, talk is cheap,show me the code


#!/usr/bin/env python
#coding:utf-8
'''
Created on 2016 years 6 month 9 day 
@author: lei.wang
'''
def diff(listA,listB):
 # Two ways to find the intersection 
 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
 # O and set 
 retC = list(set(listA).union(set(listB)))
 print "retC1 is: ",retC
 # Find the difference set, in B But not in A In the 
 retD = list(set(listB).difference(set(listA)))
 print "retD is: ",retD
 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()

Get code run up

[

retA is: [3, 4, 5]
retB is: [3, 4, 5]
retC1 is: [1, 2, 3, 4, 5, 6, 7]
retD is: [6, 7]
retE is: [6, 7]

]

In combination with the code, there are basically two ideas:

1. Use list parsing. List parsing 1 is generally faster than looping, and pythonic is more awesome.

2. After converting list to set, use various methods of set to process.

For more information about Python, please refer to Python list (list) operation Skills Summary, Python String operation Skills Summary, Python Data Structure and Algorithm Tutorial, Python Function Use Skills Summary, Python Introduction and Advanced Classic Tutorial and Python File and Directory Operation Skills Summary.

I hope this article has been helpful in Python programming.


Related articles: